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 $?;
chomp($count);
——————————-

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.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

What’s this?

You are currently reading Fastest Solution to Count Number of Lines Inside a File at Rupom Here.

meta

%d bloggers like this: