Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

while or foreach?

by BBQ (Curate)
on Dec 24, 1999 at 03:12 UTC ( [id://1363]=perlquestion: print w/replies, xml ) Need Help??

BBQ has asked for the wisdom of the Perl Monks concerning the following question:

What's the difference between these two lines?
foreach $line (<FILE>) { print $line; }
while ($line = <FILE>) { print $line; }

Isn't it curious that they even have the same length? :o)

Replies are listed 'Best First'.
RE: while or foreach?
by Anonymous Monk on Dec 24, 1999 at 00:57 UTC
    Not really, functionally they do the same thing... however, I tend to use foreach more for list manipulation, and while more for things like reading filehandles. They pretty much do the exact same thing.

Speed and Readability
by chromatic (Archbishop) on Dec 24, 1999 at 11:40 UTC
    I tried Benchmarking these, but it's just too fast to get much of a feel for what's going on inside. I'm guessing that the speed difference between the two is pretty minimal.

    Nate's in the mainstream of Good Perl Taste here. while is good for loops and reading from filehandles, while foreach is good for iterating over some sort of list, whether is is the keys of a hash or the elements of an array.

    If you're *really* into cool things, don't forget that you can do this. $_ (the current line) is assumed in those contexts. Neat, huh?

      Even worse than simply violating the "thou shalt not violate the while(<>) idiom for file iteration", I'd bet that the foreach route will slurp the entire file into an array before starting to loop over it -- something you'd almost certainly not want to do with a large (read: many-lined) file!
      Good note on $_! Which actually brings me to another question (and this ought to be a poll thing!):
      What do you prefer?
        <il>Shorter code, but cryptic reading?</il> <il>Readability but "longer self-explanatory" code</il>

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (3)
As of 2024-04-24 03:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found