Here's an answer to your question, instead of yet another way to count the number of lines in a file. ;-)

The solution mentioned in the FAQ runs much faster. Run the following code:

#!/usr/bin/perl use strict; use warnings; use Benchmark qw(timethese); my $filename = '/usr/share/dict/words'; timethese(100, { 'read_block' => sub { open(FILE, $filename) or die "Can't open file: $!"; my $lines = 0; while (read FILE, my $buffer, 4096) { $lines += ($buffer =~ tr/\n//); } close FILE; }, 'read_line' => sub { open(FILE, $filename) or die "Can't open file: $!"; while (<FILE>) {}; my $lines = $.; close FILE; } });

So, why does this happen? Well, the read_line approach above must read the file one byte at a time in case it encounters a line ending. The read_block approach reads a block of data from the disk and processes it within the Perl process, not needing to make any operating system calls.

The significance of 4096 is that disk block sizes are usually some multiple of 1024 bytes, so reading complete blocks helps the code run faster than if it were to read partial blocks.


In reply to Re: How To Count Lines In File? by tomhukins
in thread How To Count Lines In File? by Cody Pendant

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.