in reply to Looking for a better way to get the number of lines in a file...

Maybe under Unix the following is rather fast, although it is uses the external program wc:
my $length = `wc -l $filename`; chomp($length);

Best regards,
perl -e "print a|r,p|d=>b|p=>chr 3**2 .7=>t and t"

Replies are listed 'Best First'.
Re: Re: Looking for a better way to get the number of lines in a file...
by RedDog (Pilgrim) on Dec 11, 2001 at 05:15 UTC
    I have noticed that if you use wc on a file, it will also return the name of the file as well. You need to change the code as follows:
    my $string=`wc -l $filename`; my ($file,$length)=split " ",$filename; chomp($length);


    ...We will have peace, when you and all your works have perished -- and the works of your dark master to whom you would deliver us. You are a liar, Saruman, and a corrupter of men's hearts. -- Theoden in The Two Towers --
      That looks a bit off to me. First of all, $string contains the information, but you are splitting $filename. Secondly, every wc implementation that I've ever seen outputs the linecount before the filename, but you have them reversed....

      If I were going to rewrite this snippet and was forced to use wc, I might do something like:

      #!/usr/bin/perl -wT use strict; %ENV = (PATH => '/bin:/usr/bin'); # give us a happy enviornment my $filename = '/etc/services'; # filename to be checked my $length = do { my $string = `wc -l $filename`; # get output of wc die "wc error $?" if $?; # die if wc chokes for some reason no warnings 'numeric'; # turn off a pesky warning ;-) $string + 0; # numerify it with +0 }; print "length = $length\n"; # "length = 331" on my machine
      Update:
      *sigh* /g still gives me trouble some times.... The numerify line above could also have been:
      ($string =~ /\d+/g)[0];
      which would eliminate the need to turn off the warning. Therefore, the above can all be squeezed down into:
      my $length = (`wc -l $filename` =~ /\d+/g)[0]; # get output of wc die "wc error $?" if $?; # die if wc chokes for some reason

      -Blake