Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

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)

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?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1363]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2018-06-25 12:45 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.