Why does the following perl code:
for(open(my $fh, ">>", "test.txt")){
print $fh "one\n";
}
for(open(my $fh, ">>", "test.txt")){
print $fh "two\n";
}
for(open(my $fh, ">>", "test.txt")){
print $fh "three\n";
}
Write the following to test.txt?
three
two
one
Why is the order is getting reversed? My understanding is that each for block will automatically close the file when the block exits. Shouldn't this cause perl to flush any buffers before the the next block starts? I expected this code to open the file, write a line, close the file, then repeat all of those steps two more times. What am I missing?
I tested this with Perl 5.26.1, running on Ubuntu 18.04.3.
(Yes, I know I could easily get the lines to be written in the correct order by just putting all the print statements in the same block. That's not the question here. I want to understand why this behavior is happening.)
For bonus weirdness, when I run the following code:
for my $val (qw/ one two three /) {
for(open(my $fh, ">>", "test.txt")){
print $fh "$val\n";
}
}
It gives me the following output:
one
two
three
This code seems like it should be functionally identical to the previous code. Why is it behaving differently?