Akhthar Parvez K wrote:
On Wednesday 05 May 2010, Shawn H Corey wrote:
Brian wrote:
        foreach $line (<LOGFILE>) {
while (my $line = <$logfile>) would be a better idea than foreach $line.

Just curious for an explanation to this. I tend to use foreach too.
Don't they both accomplish the same thing? :)

Yes, but they go about it in different ways. The foreach loads the entire file into memory and steps through it one line at a time. The while loads only one line at a time.


foreach $line (<$fh>)
while ($line = <$fh>)

If I could explain this further for Perl beginners:
With that foreach statement, it reads the file first and creates an
array with each line as elements and that array is being looped so the
overhead is higher, whereas with that while statement, loop is
processed whilst the file is being read and hence it's more
appropriate. So while would be a better choice, more so if the file
size is higher and there's a scope of closing the file before it's
read completely.

That's what I understood. Please correct me if there was anything
incorrect with that.

Yes, foreach reads the file into a list, not an array.

perldoc -q "What is the difference between a list and an array"



John
--
The programmer is fighting against the two most
destructive forces in the universe: entropy and
human stupidity.               -- Damian Conway

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to