通过unix命令逐行传输perl输出到文件

Tec*_*ore 0 unix perl

我在unix环境中创建了一个小的perl程序:

#! /usr/bin/perl
use strict; 
use warnings; 

my $counter = 0;  
while ($counter < 10) {
  printf "%s\n", $counter;
  $counter++;  
  sleep(2);
}
Run Code Online (Sandbox Code Playgroud)

如果我在命令行启动它,它将在20秒内从0到9计数.这就是我想要的.

但是如果我使用命令将输出传输到文件(myprog.pl >> myprog.log),那么输出将在程序结束时(20秒后)立即写入.

我希望程序将它逐行写入文件.所以10秒后应该有5行myprog.log.有没有办法做到这一点?

pil*_*row 11

这是预期的缓冲行为,但您的脚本可以改变它.

#! /usr/bin/perl
use strict; 
use warnings; 

$| = 1; # <------- Enable autoflush    

my $counter = 0;  
while ($counter < 10) {
  printf "%s\n", $counter;
  $counter++;  
  sleep(2);
}
Run Code Online (Sandbox Code Playgroud)