Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

file length

Status
Not open for further replies.

sparc20

Programmer
Mar 13, 2002
56
GB
Hello , i was wondering if anyone knows how
to get the number of lines of a file while running a perl program??? is there a value for this (like NR in awk ?)

thanx
 
$n = 0;
open (FILE, &quot;<file&quot;);
++$n while(<FILE>);
print $n;
 
Or:
Code:
open(FILE, &quot;<file&quot;);
@data = <FILE>;
close FILE;
print scalar(@data);
# or
print $#data+1;

Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard. [dragon]
 
Here's another one;

open(FILE, &quot;blah&quot;) or die &quot;oooops: $!\n&quot;;

while(<FILE>) {

;

}

print &quot;No of lines is: &quot; . $. . &quot;\n&quot;;

There are some caveats to using the $. variable - see the perlvar manpage for details.

greadey
 
tsdragon, if you are just checking the file length, which could be several megabytes, using @data = <FILE> is a very heavy drain on memory.

Barbie. Leader of Birmingham Perl Mongers
 
Yeah, I know that. But it could be very short too, in which case my method is efficient, and also gives you the file in an array so you can do other things with it too. Like almost everything else in perl, there's more than one way to do it, which is the main thing I was illustrating. If I'm processing relatively small files I frequently load them into an array to make them more efficient to process. Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard. [dragon]
 
If you're on a *nix box, sometimes that OS has a good solution. Obviously, this would not be portable to a Win OS.
Code:
$num_lines = `wc -l $file_name`;

Those are backticks, not quotes. 'hope this helps

If you are new to Tek-Tips, please use descriptive titles, check the FAQs, and beware the evil typo.
 
Good call goBoating. I knew there was a *nix command to do that, but couldn't remember what it was. Tracy Dryden
tracy@bydisn.com

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard. [dragon]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top