可以在Perl中强制刷新输出吗?
我在Perl中有以下两行代码:可以在Perl中强制刷新输出吗?,perl,flush,autoflush,Perl,Flush,Autoflush,我在Perl中有以下两行代码: print "Warning: this will overwrite existing files. Continue? [y/N]: \n"; my $input = <STDIN>; print“警告:这将覆盖现有文件。是否继续?[y/N]:\N”; 我的$input=; 问题在于,在Perl脚本暂停输入之前,打印行不会执行。也就是说,Perl脚本似乎无缘无故地无限期地停止。我猜输出是以某种方式缓冲的(这就是为什么我放入了\n,但似乎没有帮
print "Warning: this will overwrite existing files. Continue? [y/N]: \n";
my $input = <STDIN>;
print“警告:这将覆盖现有文件。是否继续?[y/N]:\N”;
我的$input=;
问题在于,在Perl脚本暂停输入之前,打印行不会执行。也就是说,Perl脚本似乎无缘无故地无限期地停止。我猜输出是以某种方式缓冲的(这就是为什么我放入了\n,但似乎没有帮助)。有几种方法可以启用自动刷新:
$|++;
在开始处,或同时使用开始
块:
BEGIN{ $| = 1; }
但是,您的配置似乎有些不寻常,因为通常末尾的
\n
会触发刷新(至少是终端的刷新)。默认情况下,STDOUT在连接到终端时是行缓冲的(由LF刷新),而块缓冲的(在缓冲区满时刷新)当连接到终端以外的东西时。此外,
在STDOUT连接到终端时会刷新它
这意味着
- STDOUT未连接到终端
- 您没有打印到标准输出,或者
- 史都被搞砸了
print
在未提供句柄时打印到当前选择ed句柄,因此无论上述哪一项为真,以下操作都有效:
# Execute after the print.
# Flush the currently selected handle.
# Needs "use IO::Handle;" in older versions of Perl.
select()->flush();
或
#在启动之前随时执行。
#使当前选定的句柄在每次打印后立即刷新。
$| = 1;
是。我在util.pl文件中为此编写了一个子例程,在我的所有Perl程序中都是require
d
###########################################################################
# In: File handle to flush.
# Out: blank if no error,, otherwise an error message. No error messages at this time.
# Usage: flushfile($ERRFILE);
# Write any file contents to disk without closing file. Use at debugger prompt
# or in program.
sub flushfile
{my($OUTFILE)=@_;
my $s='';
my $procname=(caller(0))[3]; # Get this subroutine's name.
my $old_fh = select($OUTFILE);
$| = 1;
select($old_fh);
return $s; # flushfile()
}
对于那些不想像保姆一样调用flush()
每次print
后调用flush()
的人,因为它可能在循环中
或其他什么东西中,而您只想让print
不受缓冲,然后只需将其放在perl脚本的顶部:
STDOUT->autoflush(1);
此后,无需在print
之后调用flush() 这是一个很好的答案,请注意,您还可以为特定句柄设置自动刷新STDERR->autoflush(1)代码>确实如此,但请注意,默认情况下,STDERR是自动刷新的。@ikegami-根据我的经验,STDERR在默认情况下并不总是自动刷新。@ikegami-下面是一个简单的示例:perl-E'use open:std',“:encoding(UTF-8)”;打印标准“foo”;睡眠(5);说STDERR“bar”
而不是perl-E“使用open:std”,“:encoding(UTF-8)”;标准->自动刷新(1);打印标准“foo”;睡眠(5);使用CentOS Linux 7.5.1804版(Core)和为x86_64-Linux-thread-multi构建的Perl 5,版本16,subversion 3(v5.16.3),说出STDERR“bar”
@Ωmega,啊,是的,虽然底层句柄是自动刷新的,但编码层添加了另一个缓冲区,而不是。对于我来说,第一行(use IO::Handle;
)是不必要的
###########################################################################
# In: File handle to flush.
# Out: blank if no error,, otherwise an error message. No error messages at this time.
# Usage: flushfile($ERRFILE);
# Write any file contents to disk without closing file. Use at debugger prompt
# or in program.
sub flushfile
{my($OUTFILE)=@_;
my $s='';
my $procname=(caller(0))[3]; # Get this subroutine's name.
my $old_fh = select($OUTFILE);
$| = 1;
select($old_fh);
return $s; # flushfile()
}
STDOUT->autoflush(1);