Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

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

by faq_monk (Initiate)
on Oct 08, 1999 at 00:23 UTC ( #646=perlfaq nodetype: print w/replies, xml ) Need Help??

Current Perl documentation can be found at perldoc.perl.org.

Here is our local, out-dated (pre-5.6) version:

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
[LanX]: Sinai_Peninsula
[robby_dobby]: choroba: If you're talking of Eurasia, it's only true of the erstwhile Constantinople/ Ottoman empire
[LanX]: yes correct, but Sinai is not on the other side
[LanX]: Organizing a YAPC in a tourist ressort is not a bad idea ...
[LanX]: ... and we could swap to our first YAPC Africa the following year when organizing in Hurghada
[robby_dobby]: LanX: Well volunteered!
[LanX]: ... just ... ppl would be to afraid of terrorist attacks
[choroba]: python guerrila?
[robby_dobby]: if I do make it, I can at least savour their local tea! :-)
[LanX]: oh they have sleper cells everywhere

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (15)
As of 2017-04-24 16:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I'm a fool:











    Results (442 votes). Check out past polls.