![]() |
|
Keep It Simple, Stupid | |
PerlMonks |
How do I count the number of lines in a file?by faq_monk (Initiate) |
on Oct 08, 1999 at 00:23 UTC ( #646=perlfaq nodetype: print w/replies, xml ) | Need Help?? |
Current Perl documentation can be found at perldoc.perl.org. Here is our local, out-dated (pre-5.6) version: One fairly efficient way is to count newlines in the file. The following program uses a feature of tr///, as documented in the perlop manpage. If your text file doesn't end with a newline, then it's not really a proper text file, so this may report one fewer line than you expect.
$lines = 0; open(FILE, $filename) or die "Can't open `$filename': $!"; while (sysread FILE, $buffer, 4096) { $lines += ($buffer =~ tr/\n//); } close FILE; This assumes no funny games with newline translations.
|
|