I created a small perl programm in a unix enviroment:
#! /usr/bin/perl
use strict;
use warnings;
my $counter = 0;
while ($counter < 10) {
printf "%s\n", $counter;
$counter++;
sleep(2);
}
If I start this at command line it will count from 0 to 9 in 20 seconds. That's what I want.
But if I use a command to transfer output to a file (myprog.pl >> myprog.log
) then the output will be written at once at the end of the program (after 20 sec).
I want that the program writes it output line by line to the file. So after 10 seconds there s开发者_JS百科hould be 5 lines in myprog.log
. Is there a way to do this?
That's expected buffering behavior, but your script can change that.
#! /usr/bin/perl
use strict;
use warnings;
$| = 1; # <------- Enable autoflush
my $counter = 0;
while ($counter < 10) {
printf "%s\n", $counter;
$counter++;
sleep(2);
}
An interesting discussion on the subject: http://perl.plover.com/FAQs/Buffering.html
精彩评论