2009-06-22 90 views
4

我正在看Perl中的一些旧代码,其中作者在第一行中具有书写器 $| = 1

但是,该代码没有任何打印语句,它使用system命令调用C++二进制文件。现在我读到$|将在每次打印后强制刷新。所以它会以任何方式影响系统命令的输出,或者我可以安全地删除该行。

感谢 阿文德

回答

7

我不这么认为。 $ |会影响Perl运行的方式,而不是任何外部可执行文件。

您应该安全地将其删除。

perldoc - perlvar:States“如果设置为非零,则在当前选择的输出通道上每次写入或打印后立即强制刷新一次”。我认为这里重要的是“当前选择的输出通道”。外部应用程序将拥有自己的输出通道。

5

像这样的问题往往是容易写一个简单的程序,显示的行为是什么:

#!/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运行。

5

这是你可以轻松检查自己的东西。创建一个缓冲区的程序,如打印一系列点。你应该在十秒钟后一下子看到输出,因为输出缓冲:

 
#!perl 

foreach (1 .. 10) 
    { 
    print "."; 
    sleep 1; 
    } 

print "\n"; 

现在,尝试设置$|,并呼吁这跟system

% perl -e "$|++; system(qq|$^X test.pl|)"; 

对于我的测试情况下,$ |值不会影响子进程中的缓冲。