Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Why is the STDOUT line printed after the STDERR line?

I completly don't understand this behaviour.

I have a very simple Perl script:


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?

like image 565
bessarabov Avatar asked Dec 26 '22 01:12


1 Answers

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.

like image 88
Leon Timmermans Avatar answered Jan 05 '23 16:01

Leon Timmermans