Special_K has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to figure out how perl determines the order in which to output STDOUT and STDERR text, both to a terminal and to a file. Consider the following code:



#!/tool/bin/perl -w use strict; my $i = 0; my @array; for ($i = 0; $i < 100; $i++) { printf("element $i of array = "); printf("%s\n", $array[$i]); }


If I run this code in a terminal, the output is as follows:



> ./stderr_test.pl Use of uninitialized value in printf at ./stderr_test.pl line 11. element 0 of array = Use of uninitialized value in printf at ./stderr_test.pl line 11. element 1 of array = Use of uninitialized value in printf at ./stderr_test.pl line 11. element 2 of array = Use of uninitialized value in printf at ./stderr_test.pl line 11. element 3 of array = Use of uninitialized value in printf at ./stderr_test.pl line 11. element 4 of array = ...


As you can see, the stdout text is interleaved with the stderr, which is what I would expect based on the order of the printf statements. If I redirect the text to a file however, the result is different:



> ./stderr_test.pl > & log


where log contains:



Use of uninitialized value in printf at ./stderr_test.pl line 13. Use of uninitialized value in printf at ./stderr_test.pl line 13. Use of uninitialized value in printf at ./stderr_test.pl line 13. ... element 0 of array = element 1 of array = element 2 of array = ...


As you can see, in this case perl first outputs all the stderr output, then outputs all the stdout output. Why does it do this?



Why is the behavior different when I output to a file vs. the terminal?



More importantly, how can I force the file output to appear in the correct order? Debugging is much easier when printed statements appear in programatic order.



I tried adding the following to my code above:



open(STDERR,'>&', STDOUT);


but that didn't make any difference in my output file.

Replies are listed 'Best First'.
Re: ordering of stdout and stderr outputs
by Anonymous Monk on Dec 22, 2014 at 17:43 UTC
      Wow, thanks. That answers my question perfectly. Incidentally that article is the first thing that appears on Google when I search for even the generic "perl buffering". Had I known that "buffering" was the proper term for the behavior I was seeing I could have found that article on my own.