Fastest Solution to Count Number of Lines Inside a File
June 14, 2007 § Leave a comment
Here is another PERL stuff to share.
Many systems have a wc program to count lines in a file:
$count = `wc -l
die “wc failed: $?” if $?;
You could also open the file and read line-by-line until the end, counting lines as you go:
$count++ while ;
# $count now holds the number of lines read
Here’s the fastest solution, assuming your line terminator really is “\n”:
$count += tr/\n/\n/ while sysread(FILE, $_, 2 ** 16);
Enjoy PERL. Enjoy Programming.