Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

while or foreach?

by BBQ (Deacon)
on Dec 24, 1999 at 03:12 UTC ( #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)

Comment on while or foreach?
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?

      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>
      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!

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (12)
As of 2014-11-24 16:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (143 votes), past polls