On Mon, Jan 17, 2011 at 12:52 AM, Shmuel Fomberg <ow...@semuel.co.il> 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 Perl@perl.org.il http://mail.perl.org.il/mailman/listinfo/perl