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
In reply to •Re: file processing, while and foreach: a n00b experience
by merlyn
|
|