in reply to Example for EOF
The function eof will return true after you've read all of the lines of the file. A simple example:
open FH, '<', 'file.txt' or die ("Can't read file: $!"); until( eof(FH) ) { print <FH>; }
However, you rarely need to use eof() to accomplish what you are asking about. Imagine that you want read in a text file and, when finished, print the average length of lines (excluding any ending whitespace) to the screen, along with the number of lines. You might do that this way:
open FH, '<', 'file.txt' or die ("Can't read file: $!"); my ($lines, $total_length); while (<FH>) { s/\s+$//s; # trims all traling whitespace, including \n ++$lines; $total_length += length($_); } #loop ends automatically when you reach EOF printf "File had %d lines, with an average length of %d chars\n", $lines, ($total_length / $lines);
You see? You don't need to check for EOF by hand, as Perl does it for you.
|
|---|