Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

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?
Replies are listed 'Best First'.
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?

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2015-11-26 04:34 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (696 votes), past polls