[olug] Fwd: Daily Perl FAQ - How do I count the number of lines in a file?

Jay Hannah jay at jays.net
Sun Nov 9 23:15:49 UTC 2003


Hey Rube,

Been searching for a longer, hard to remember version of "wc -l"? Your 
wait is over.

Grin,

j
http://www.rube-goldberg.com/html/pencil_sharpener.htm
Omaha Perl Mongers: http://omaha.pm.org


Begin forwarded message:
> From: perlreply at faq-by-day.org
> Date: Thu Nov 6, 2003  5:58:30 AM America/Chicago
> To: jay at jays.net
> Subject: Daily Perl FAQ - How do I count the number of lines in a file?
>
>
> This is a daily mailing from the Perl FAQ a Day website.
> For subscription info, or to have your address removed from
> the mailing list, please see http://perl.faq-by-day.org/
>
> Question:
> How do I count the number of lines in a file?
>
>     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.



More information about the OLUG mailing list