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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.