flush perl’s print buffer
February 16th, 2006 by Lawrence David
sometimes, if you put a print statement inside of a loop that runs really really quickly, you won’t see the output of your print statement until the program terminates. sometimes, you don’t even see the output at all. the solution to this problem is to “flush” the output buffer after each print statement; this can be performed in perl with the following command:
$|++;
[update]
as has been pointed out by r. schwartz, i’ve misspoken; the above command causes print to flush the buffer preceding the next output.
Actually, you can also use “$| = 1″ to do that, and some would consider that a bit less obscure.
Also, that doesn’t flush the buffer. It tells print to flush the buffer on the next output. I think you know that, but it might not be clear reading that.
thanks for the note randal – i’ve modified my original post accordingly.
You might also use the English module and then you can do:
$OUTPUT_AUTOFLUSH = 1;
thanks for the tip. It saved the day.
** handing treasure chest **
** got a Courage-Mushroom **
** feel free to use it anytime you’ve got the PhD blues **
sweet — thanks
Hello, I’m newcomer to PERL programming, this instruction “$|=1″ should be inside the loop or this is required one time before the loop.
Thank you for your support!!
Hi Adolfo,
It goes inside of the loop.
Good luck!
Nope, it’s one time:
$| = 1;
for($i=0;$i<10;$i++){
print “=”;
sleep 1;
}
print “\n”;
$| = 0;
for($i=0;$i<10;$i++){
print “=”;
sleep 1;
}
The second line is printed “whole” after 10s, while the firsat one is printed one = each second.
Also, printing “\n” flushes the buffer, which you can verify by modifying the last print to “=\n”.
Your correction is not right, as merry points out.
From “perldoc perlvar”:
HANDLE->autoflush(EXPR)
$OUTPUT_AUTOFLUSH
$| If set to nonzero, forces a flush right away and after every write or print on the currently selected output channel. Default is 0 (regardless of whether the channel is really buffered by the system or not; $| tells you only whether you’ve asked Perl explicitly to flush after each write). STDOUT will typically be line buffered if output is to the terminal and block buffered otherwise. Setting this variable is useful pri- marily when you are outputting to a pipe or socket, such as when you are running a Perl program under rsh and want to see the output as it’s happening. This has no effect on input buffering. See “getc” in perlfunc for that. (Mnemonic: when you want your pipes to be piping hot.)
-Dan
Also (re: merry’s post), printing “\n” does not flush, unless $| is already set to non-zero.
Thanks for posting this!
All I can say is: wow, that was obscure.
Sweet mangoes! Thanks for this tip.
Excellent. Helped me solve a frustrating problem. Thanks!
[...] å‚考:http://desk.stinkpot.org:8080/tricks/index.php/2006/02/flush-perls-print-buffer/ Like this:LikeBe the first to like this post. Comments RSS feed [...]