http://www.perlmonks.org?node_id=758656

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

Replies are listed 'Best First'.
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 Corion (Patriarch) on Apr 20, 2009 at 13:18 UTC
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