我正在查看 Perl 中的一些旧代码,作者
$| = 1
在第一行写过。
但是代码没有任何打印语句,它使用system
命令调用 C++ 二进制文件。现在我读到$|
每次打印后都会强制刷新。它是否会以任何方式影响系统命令的输出,或者我可以安全地删除该行。
谢谢阿文德
我不相信。$| 将影响 Perl 的运行方式,而不是任何外部可执行文件。
您应该可以安全地删除它。
perldoc - perlvar:状态“如果设置为非零,则在当前选定的输出通道上的每次写入或打印之后立即强制刷新。 ”。我认为这里重要的是“当前选择的输出通道”。外部应用程序将拥有自己的输出通道。
对于这样的问题,通常很容易编写一个简单的程序来显示行为是什么:
#!/usr/bin/perl
use strict;
use warnings;
if (@ARGV) {
output();
exit;
}
print "in the first program without \$|:\n";
output();
$| = 1;
print "in the first program with \$|:\n";
output();
print "in system with \$|\n";
system($^X, $0, 1) == 0
or die "could not run '$^X $0 1' failed\n";
$| = 0;
print "in system without \$|\n";
system($^X, $0, 1) == 0
or die "could not run '$^X $0 1' failed\n";
sub output {
for my $i (1 .. 4) {
print $i;
sleep 1;
}
print "\n";
}
由此我们可以看出,设置$|
对运行的程序没有影响system
。
这是您可以轻松检查自己的事情。创建一个缓冲很重要的程序,例如打印一系列点。由于输出被缓冲,您应该在十秒后立即看到所有输出:
#!perl foreach ( 1 .. 10 ) { 打印 ”。”; 睡觉1; } 打印“\n”;
现在,尝试设置$|
和调用它system
:
% perl -e "$|++; system( qq|$^X test.pl| )";
对于我的测试用例, $| value 不影响子进程中的缓冲。