I completly don't understand this behaviour.
I have a very simple Perl script:
#!/usr/bin/perl
use strict;
use warnings;
print "line 1\n";
print STDERR "line 2\n";
If I run it from console I will get what I expect:
$ perl a.pl
line 1
line 2
But if I redirect it to file, I will get the lines in the reverse order:
$ perl a.pl &> a
$ cat a
line 2
line 1
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