代码之家  ›  专栏  ›  技术社区  ›  Arvind

Perl的$|设置是否影响系统命令?

  •  4
  • Arvind  · 技术社区  · 17 年前

    我正在看一些Perl中的旧代码,作者在其中编写了 $| = 1 在第一行。

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

    谢谢 阿文德

    3 回复  |  直到 17 年前
        1
  •  7
  •   Xetius    17 年前

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

    你应该可以安全地移除它。

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

        2
  •  5
  •   Chas. Owens    17 年前

    对于这样的问题,通常很容易编写一个简单的程序来显示行为:

    #!/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 .

        3
  •  5
  •   brian d foy    17 年前

    这是你可以轻松检查自己的东西。创建一个缓冲很重要的程序,比如打印一系列点。由于输出已缓冲,因此应在10秒后立即看到所有输出:

    #!perl
    
    foreach ( 1 .. 10 )
        {
        print ".";
        sleep 1;
        }
    
    print "\n";
    

    $| 把这个叫做 system

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

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