Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

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

by vinoth.ree (Prior)
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 avoiding work at the Monastery: (8)
As of 2015-07-05 15:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (67 votes), past polls