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


In reply to Re3: Looking for a better way to get the number of lines in a file... by blakem
in thread Looking for a better way to get the number of lines in a file... by coec

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.