Perl can't seem to do two
while loops on the same read-only filehandle, as I painfully found out after spending upwards of three hours troubleshooting a long and fairly complex script.
The problem can be condensed to this:
open (INPUTFILE, "<:encoding(UTF-8)", "in.txt") or die "Can't open fil
+e: $!";
for (my $i = 1; $i < 5; $i++) {
print "\n-----------------------LOOP $i-----------------------\n";
while ($line = <INPUTFILE>) {
print "line $.: $line\n";
}
}
close INPUTFILE;
This prints the contents of the file in loop one as expected, but then it prints an empty loop 2, 3 and 4.
I have to close and reopen the filehandle in each loop to make it work:
for (my $i = 1; $i < 5; $i++) {
open (INPUTFILE, "<:encoding(UTF-8)", "in.txt") or die "Can't open
+ file: $!";
print "\n-----------------------LOOP $i-----------------------\n";
while ($line = <INPUTFILE>) {
print "line $.: $line\n";
}
close INPUTFILE;
}
As a point of interest, if I just reopen the fh in each loop without closing it (i.e. move the
close out of the loop) then the program still works but the line numbers are not reset after each loop.
Is this behaviour intentional? Should I have known this to begin with? Does this behaviour serve any purpose or have any benefit? It certainly seems broken to me.
Even this simple code doesn't work as I would expect it to:
print "First loop:\n\n";
while (<DATA>) {
print;
}
print "\n\nSecond loop:\n\n";
while (<DATA>) {
print;
}
__DATA__
first line
second line
third line
I'm on Win7 with perl 5.10.0, by the way. (I'm using an old version because ppm is broken in new versions.) I also tested this on 5.10.1 on Ubuntu and got the same result.