Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

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

by Kage (Scribe)
on Dec 10, 2001 at 21:54 UTC ( [id://130724]=note: print w/replies, xml ) Need Help??


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

Simple..
$file="filename.ext"; open(COUNT,"$file") || err("Oops.. $!"); @lines = <COUNT>; close(COUNT); $count="0"; foreach $line (@lines) { $count++; } print "Content-type: text/html\n\n"; print "$file's length is $count";
10 lines if you don't count the line breaks
"I am loved by few, hated by many, and wanted by plenty." -Kage (Alex)
SkarySkriptz
  • Comment on Re: Looking for a better way to get the number of lines in a file...
  • Download Code

Replies are listed 'Best First'.
Re: Re: Looking for a better way to get the number of lines in a file...
by belden (Friar) on Dec 11, 2001 at 00:21 UTC
    This is an adaptation of... um... I think recipe 8.6 in Cookbook, "Picking a random line from a file", though I may have seen it elsewhere. (Corrections? Credit?)
    #!/usr/bin/perl open ( FH,'data' ) or die ( "data: $!\n" ); while( <FH> ) { if ( eof ( FH ) ) { print $. } }
    What I like about this is that you aren't storing anything in memory - so this should wade through a 2GB file (as mentioned fearfully later in this thread) fairly quickly.

    blyman setenv EXINIT 'set noai ts=2'

Re: Re: Looking for a better way to get the number of lines in a file...
by Biker (Priest) on Dec 10, 2001 at 22:01 UTC

    Reading in a full file into memory scares me. One day, someone will feed a 2GB file...

    Having said that, @lines in your example already gives the number of elements in the array, where each element should contain a line. No need to count them.

    f--k the world!!!!
    /dev/world has reached maximal mount count, check forced.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2024-03-29 22:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found