Readline using foreach and while



Hi,
Is there any difference in reading a file using a while or a
foreach in perl?

If I do :
foreach(<filehandle>) {
my $local = <filehandle>; # I assumed I will increment the file
descriptor here
print " local $local\n";
}

But if I do :
while(<filehandle>) {
my $local = <filehandle>; # I assumed I will increment the file
descriptor here
print " local $local\n";
}
It works fine....
Is there something wrong or some difference in the two operations? Or
am I missing something?

Thanks and Regards,
Saurabh


Small example to replicate the issue
my file name is test.pl

#!/usr/bin/perl

open (handle,"test.pl")||die "\n $0 Could not open $! \n";

my $line = <handle>;#read a line till \n or eof
print " line $line";
#foreach(<handle>){ # Not as expected
while(<handle>){ # Works as expected
$line =<handle>;#read a line till \n or eof

print " in side $line";
$line =<handle>;#read a line till \n or eof
print " in side $line";
$line =<handle>;#read a line till \n or eof
}
close handle;
.



Relevant Pages

  • Re: Readline using foreach and while
    ... Saurabh Jain wrote: ... foreach in perl? ... Reading a file line by line works only with while. ... foreach reads the ...
    (comp.lang.perl.misc)
  • Re: Readline using foreach and while
    ... Is there any difference in reading a file using a while or a ... foreach in perl? ... The foreach version seems to first read the whole of the file into an ... The while seems to increment through the loop. ...
    (comp.lang.perl.misc)
  • Re: Readline using foreach and while
    ... Is there any difference in reading a file using a while or a ... foreach in perl? ... array, and then go through it line by line: ... Perl isn't a toolbox, but a small machine shop where you ...
    (comp.lang.perl.misc)
  • Re: strange select() behavior
    ... cases a descriptor "shall be considered ready for reading". ... If is ready-to-run at the ... non-existent guarantee that must be in the standard somewhere came ...
    (comp.unix.programmer)
  • Re: non blocking sockets
    ... >> determined that the socket was ready. ... > Upon successful completion, the pselector selectfunction shall ... > arguments to indicate which file descriptors are ready for reading, ... > descriptor shall be considered ready for reading.) ...
    (comp.unix.programmer)