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.

-- 
Regards,
Akhthar Parvez K
http://Tips.SysAdminGUIDE.COM
UNIX is basically a simple operating system, but you have to be a genius to 
understand the simplicity - Dennie Richie

-- 
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