你能用perl强制刷新输出吗?

Joh*_*ohn 19 perl flush autoflush

我在perl中有以下两行:

print "Warning: this will overwrite existing files.  Continue? [y/N]: \n";
my $input = <STDIN>;
Run Code Online (Sandbox Code Playgroud)

问题是在perl脚本暂停输入之前,打印行没有执行.也就是说,perl脚本似乎无缘无故地无缘无故地停止.我猜测输出是以某种方式缓冲的(这就是为什么我把\n放入,但这似乎没有帮助).我对perl很新,所以我很感激有关如何解决这个问题的任何建议.

ike*_*ami 30

默认情况下,STDOUT在连接到终端时进行行缓冲(由LF刷新),在连接到终端以外的其他位置时进行块缓冲(在缓冲区满时刷新).此外,<STDIN>当STDOUT连接到终端时刷新STDOUT.

这意味着

  • STDOUT未连接到终端,
  • 你没有打印到STDOUT,或
  • STDOUT被搞砸了.

printselect当没有提供句柄时,打印到当前ed句柄,因此无论上述哪一项都是如此,以下内容将起作用:

# Execute after the print.
# Flush the currently selected handle.
# Needs "use IO::Handle;" in older versions of Perl.
select()->flush();
Run Code Online (Sandbox Code Playgroud)

要么

# Execute anytime before the <STDIN>.
# Causes the currently selected handle to be flushed immediately and after every print.
$| = 1;
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的答案,请注意您还可以为特定句柄`STDERR-> autoflush(1)设置autoflush;` (3认同)

Die*_*lla 8

有几种方法可以打开autoflush:

$|++;
Run Code Online (Sandbox Code Playgroud)

在开头,或者还有一个BEGIN块:

BEGIN{ $| = 1; }
Run Code Online (Sandbox Code Playgroud)

但是,您的配置似乎有些不寻常,因为通常\n最后会触发刷新(至少是终端).


typ*_*gic 8

对于那些不想像保姆一样调用flush()follow every的人,因为它可能在 a或其他东西中,而您只是希望不缓冲,那么只需将其放在 perl 脚本的顶部部分即可:printloopprint

STDOUT->autoflush(1);
Run Code Online (Sandbox Code Playgroud)

此后,无需再调用flush()after print