[英]Transfer perl output line by line to a file via unix command
I created a small perl programm in a unix enviroment:我在 unix 环境中创建了一个小型 perl 程序:
#! /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.如果我在命令行启动它,它将在 20 秒内从 0 计数到 9。 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).但是,如果我使用命令将 output 传输到文件(
myprog.pl >> myprog.log
),那么 output 将在程序结束时立即写入(20 秒后)。
I want that the program writes it output line by line to the file.我希望程序将它 output 逐行写入文件。 So after 10 seconds there should be 5 lines in
myprog.log
.所以 10 秒后
myprog.log
中应该有 5 行。 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关于这个主题的有趣讨论: http://perl.plover.com/FAQs/Buffering.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.