S
Saurabh Jain
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;
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;