RSS .92| RSS 2.0| ATOM 0.3
  • Home
  • About Me
  • My Publications
  • My Work Domain
  • phpResource Feeds

    Fastest Solution to Count Number of Lines Inside a File

    Here is another PERL stuff to share.

    Many systems have a wc program to count lines in a file:
    $count = `wc -l < $file`; 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, "< $file") or die "can't 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.

    Leave a Reply

    You must be logged in to post a comment.