我有一个在安装了Perl 5.8.8的旧CentOS 5.6服务器上运行的Perl脚本.不幸的是,我无法升级操作系统或在此服务器上运行的Perl版本.
当我从命令提示符运行此脚本时,尽管有$| = 1;在脚本顶部的语句(在全局范围内),它似乎仍然缓冲输出到控制台(通过ssh会话).
#!/usr/bin/perl $| = 1; &writelog("Started..."); # Do work with lots of writelog'ing &writelog("...Done."); exit(0); sub writelog { # This is greatly simplified for the purpose of this question my ($logentry) = @_; my $logfile = "/var/log/thelog.log"; my $logline = "$logentry\n"; print $logline; open (LOGFILE,">>$logfile"); print LOGFILE,"$logline"; close (LOGFILE); }
是否为$|的值只影响当前范围内的输出,即在这种情况下脚本的全局范围?或者,在上面的示例中,是否应该通过writelog中的print语句立即刷新STDOUT / LOGFILE?
解决方法
每
perlvar
,$|具有全局范围,它仅适用于当前选定的输出通道.这是任何程序开头的STDOUT,但可以通过1-arg select调用进行更改.
$| = 1; # set autoflush on STDOUT open LOGFILE,'>log'; my $fh = select LOGFILE; # change "selected output channel" $| = 1; # set autoflush on LOGFILE select $fh; # restore STDOUT as "selected output channel" $| = 0; # turnoff autoflush on STDOUT