问题
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?
回答1:
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.
回答2:
Don't use $|, use autoflush instead.
STDOUT->autoflush(1);
STDERR->autoflush(1);
See http://perldoc.perl.org/IO/Handle.html
来源:https://stackoverflow.com/questions/17378189/why-is-the-stdout-line-printed-after-the-stderr-line