http://www.perlmonks.org?node_id=238343


in reply to foreach question

Hi ,

The script with a while to read is :

#!perl use strict; my $ln = 9; my $contents; open (Fnm , "a.dat"); while ($contents = <Fnm>){ chomp; if ($ln == 9){ close Fnm; $ln = 0; } print "[ $contents ]\n"; } __END__ [ one ]


The line that shows is just the first one after closing the contents at the start of the loop

The script with the foreach to read is :
#!perl use strict; my $ln = 9; my $contents; foreach $contents(<Fnm>){ chomp; if ($ln == 9){ close Fnm; $ln = 0; } print "[ $contents ]\n"; } __END__ [ one ] [ next ] [ next ] [ next ] [ next ]


The line that shows is all in the data , even if one closes the file at the start of the foreach , cause the contents are first stored in an anonymous array and then read from that array and hence the foreach is not that one uses to read large chunk of data