Why is the STDOUT line printed after the STDERR line?

I do not understand this behavior.

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 the console, I will get what I expect:

 $ perl a.pl line 1 line 2 

But if I redirect it to a 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 of STDOUT + STDERR to a file with the same order that I get in the console?

+4
source share
2 answers

This is the effect of buffering. When outputting to the terminal, Perl (like stdio) uses string-based buffering, which will give the expected effect. When outputting to a file, it uses block buffering (usually 4k or 8k blocks), so it will only hide at the end of the program.

The difference you observe is that STDERR is unbuffered, unlike most other pens.

The easiest way to get around this problem is to enable autorun in STDOUT using the special variable $| . See perlvar for more details.

+10
source

Do not use $ |, use autoflush instead.

 STDOUT->autoflush(1); STDERR->autoflush(1); 

See http://perldoc.perl.org/IO/Handle.html

0
source

Source: https://habr.com/ru/post/1488825/


All Articles