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

Whatís the difference between iterating over a file with foreach or while in Perl?

by vinoth.ree (Parson)
on Apr 20, 2009 at 10:04 UTC ( #758656=perlquestion: print w/ replies, xml ) Need Help??
vinoth.ree has asked for the wisdom of the Perl Monks concerning the following question:

I got this question from this site

question

They would have given some answers, but I did not get the clarification, thats why I posted this question here to get more clarification I am sorry that I not informed the site where I got this question pardon me! please

I have a filehandle FILE in Perl, and I want to iterate over all the lines in the file. Is there a difference between the following?

while (<FILE>) { # do something } and foreach (<FILE>) { # do something }
Vinoth,G

Comment on Whatís the difference between iterating over a file with foreach or while in Perl?
Download Code
Re: Whatís the difference between iterating over a file with foreach or while in Perl?
by almut (Canon) on Apr 20, 2009 at 10:10 UTC
    Is there a difference ...?

    Yes, the foreach will read the entire file into memory before it starts to '# do something', while the while will process the file line by line (unless you've changed the default input record separator $/).  In the foreach case, the <FILE> is evaluated in list context, in the while case in scalar context.

Re: Whatís the difference between iterating over a file with foreach or while in Perl?
by Anonymous Monk on Apr 20, 2009 at 10:25 UTC
    readline in scalar context (while) returns one line, but in list context (foreach) returns all lines
Re: Whatís the difference between iterating over a file with foreach or while in Perl?
by Corion (Pope) on Apr 20, 2009 at 13:18 UTC

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (6)
As of 2014-08-23 00:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (168 votes), past polls