Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

•Re: file processing, while and foreach: a n00b experience

by merlyn (Sage)
on Aug 27, 2003 at 13:06 UTC ( [id://287025]=note: print w/replies, xml ) Need Help??


in reply to file processing, while and foreach: a n00b experience

This is actually such a common confusion that we address it specifically in Learning Perl.

foreach always takes a list. A filehandle-read in a list context always reads the entire file into memory.

while wants a boolean, which is a special kind of scalar. The solitary filehandle-read operation is macro-expanded to reading the filehandle in a scalar context (one chunk at a time) into $_, and verifying that we're not yet at end of file.

So, while they may look similar, and in some ways act similar, they accomplish their task in completely different mechanisms.

Another thing to notice is the value of $. during the loop. In the foreach case, we've read the entire file already so the value is the number of lines of the file. In the while case, it'll be the current line number.

-- Randal L. Schwartz, Perl hacker
Be sure to read my standard disclaimer if this is a reply.

  • Comment on •Re: file processing, while and foreach: a n00b experience

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://287025]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (6)
As of 2024-04-19 07:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found