Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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.


In reply to •Re: file processing, while and foreach: a n00b experience by merlyn
in thread file processing, while and foreach: a n00b experience by Ryszard

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (6)
As of 2024-04-23 17:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found