Hi sawyer.
When he wrote 'for', I thought about C-style for, and not foreach. foreach (<$fh>)... never occurred to my to do it that way.. Shmuel. On 2011/01/17 11:15, sawyer x wrote: > On Mon, Jan 17, 2011 at 12:52 AM, Shmuel Fomberg <[email protected] > <mailto:[email protected]>> wrote: > > Hi All. > > > Hey! > > Why would anyone read a file in a for loop? > > > If you read using a while(), you're reading one line at a time, > because while() has to run the code in the condition and evaluate the > result as a boolean. If you're reading using foreach(), you're forcing > the condition to be evaluated to a list that you will then iterate over. > > Basically meaning that: > foreach my $line (<$fh>) { ... } > > # is equal to: > my @lines = <$fh>; > foreach my $line (@lines) { ... } > --- > And that: > while ( my $line = <$fh> ) { ... } > > # is equal to: > while (1) { > eof($fh) and last; > my $line = <$fh>; # get single line > ... > } > --- > > I think what chromatic meant was that you need to *know* what the > difference is. I don't personally understand *why* someone would > prefer foreach() over while(), but I know what it really means: > pre-evaluation of all accounts, which is heavier on the memory. > > Hope that helps, > Sawyer. > > > _______________________________________________ > Perl mailing list > [email protected] > http://mail.perl.org.il/mailman/listinfo/perl _______________________________________________ Perl mailing list [email protected] http://mail.perl.org.il/mailman/listinfo/perl
