Instead of a bareword, you can create a filehandle using a scalar variable. This makes things like passing a filehandle as a subroutine argument, storing them in arrays and hashes and controlling its scope, much easier.
# Typically done with a lexical variable because that way, you can ensure to get a variable without a value
my $rocks_fh; # It's common practise to put '_fh' on the end of these to remember they are filehandles
open $rocks_fh, '<', 'rocks.txt'
or die "Could not open rocks.txt: $!";
# Combine the two statements so you declare the lexical variable along with the open:
open my $rocks_fh, '<', 'rocks.txt';
or die "Could not open rocks.txt: $!";
# Once that variable is set up, you can use it the same way as the bareword version:
while(<$rocks_fh>) {
chomp;
...
}
# Output filehandle example:
open my $rocks_fh, '>>', 'rocks.txt'
or die "Could not open rocks.txt: $!";
foreach my $rock (qw(slate lava granite)) {
say $rocks_fh $rock
}
print $rocks_fh "limestone\n";
close $rocks_fh;