FAQ 5.3 How do I count the number of lines in a file?

P

PerlFAQ Server

This is an excerpt from the latest version perlfaq5.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .

--------------------------------------------------------------------

5.3: How do I count the number of lines in a file?

(contributed by brian d foy)

Conceptually, the easiest way to count the lines in a file is to simply
read them and count them:

my $count = 0;
while( <$fh> ) { $count++; }

You don't really have to count them yourself, though, since Perl already
does that with the $. variable, which is the current line number from
the last filehandle read:

1 while( <$fh> );
my $count = $.;

If you want to use $., you can reduce it to a simple one-liner, like one
of these:

% perl -lne '} print $.; {' file

% perl -lne 'END { print $. }' file

Those can be rather inefficient though. If they aren't fast enough for
you, you might just read chunks of data and count the number of
newlines:

my $lines = 0;
open my($fh), '<:raw', $filename or die "Can't open $filename: $!";
while( sysread $fh, $buffer, 4096 ) {
$lines += ( $buffer =~ tr/\n// );
}
close FILE;

However, that doesn't work if the line ending isn't a newline. You might
change that "tr///" to a "s///" so you can count the number of times the
input record separator, $/, shows up:

my $lines = 0;
open my($fh), '<:raw', $filename or die "Can't open $filename: $!";
while( sysread $fh, $buffer, 4096 ) {
$lines += ( $buffer =~ s|$/||g; );
}
close FILE;

If you don't mind shelling out, the "wc" command is usually the fastest,
even with the extra interprocess overhead. Ensure that you have an
untainted filename though:

#!perl -T

$ENV{PATH} = undef;

my $lines;
if( $filename =~ /^([0-9a-z_.]+)\z/ ) {
$lines = `/usr/bin/wc -l $1`
chomp $lines;
}



--------------------------------------------------------------------

The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in
perlfaq.pod.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top