I completly don't understand this behaviour.
I have a very simple Perl script:
print "line 1\n";
print STDERR "line 2\n";
If I run it from console I will get what I expect:
$ perl a.pl
But if I redirect it to file, I will get the lines in the reverse order:
$ perl a.pl &> a
$ cat a
How can I capture all the outputs STDOUT+STDERR to the file with the same order I get in the console?
This is an effect of buffering. When outputting to a terminal, Perl (just as stdio) uses line based buffering, which will give the expected effect. When outputting to a file, it uses block buffering (typically 4k or 8k blocks), hence it will only flush on program end.
The difference you're observing is because STDERR is unbuffered, unlike most other handles.
The easiest way to circumvent this issue is to enable autoflushing on STDOUT, using the
$| special variable. See perlvar for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!Donate Us With