Perl Script : File handles

File handles
To read the contents of a file, you have to use the open operator to get a file handle, and then use the file handle to read lines.

The operand of open is a list of two terms: an arbitrary name for the file handle,and the name of the file you want to open. The name of the file I want to open is /usr/share/dict/words, which contains a long list of English words.
open FILE, "/usr/share/dict/words";

In this case, the identifier FILE is global. An alternative is to create a local variable that contains an indirect file handle.
open my $fh, "/usr/share/dict/words";

By convention, the name of a global variable is all capital, and the name of a local variable is lower case. In either case, we can use the angle operator to read
a line from the file:

my $first = <FILE>;
my $first = <$fh>;

To be more precise, I should say that in a scalar context, the angle operator reads one line. What do you think it does in a list context?
When we get to the end of the file, the angle operator returns undef, which is a special value Perl uses for undefined variables, and for unusual conditions like the end of a file. Inside a while loop, undef is considered a false truth value,
so it is common to use the angle operator in a loop like this:
while (my $line = <FILE>) {
print $line;
}

No comments:

Post a Comment