Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

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 ( [id://130831]=note: print w/replies, xml ) Need Help??


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

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 --
  • Comment on Re: Re: Looking for a better way to get the number of lines in a file...
  • Download Code

Replies are listed 'Best First'.
Re3: Looking for a better way to get the number of lines in a file...
by blakem (Monsignor) on Dec 11, 2001 at 05:56 UTC
    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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://130831]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2024-04-26 04:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found