Fastest Solution to Count Number of Lines Inside a File

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:

open(FILE, ”
$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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.