Clear questions and runnable code get the best and fastest answer |
|
PerlMonks |
•Re: file processing, while and foreach: a n00b experienceby merlyn (Sage) |
on Aug 27, 2003 at 13:06 UTC ( [id://287025]=note: 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 Section
Meditations
|
|