【问题标题】:Does Perl's $| setting affect system commands?Perl 的 $|设置影响系统命令?
【发布时间】:2009-06-22 10:20:32
【问题描述】:

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

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

谢谢 阿文德

【问题讨论】:

    标签: perl buffering


    【解决方案1】:

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

    您应该可以安全地删除它。

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

    【讨论】:

      【解决方案2】:

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

      #!/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】:

        这是您可以轻松检查的内容。创建一个缓冲很重要的程序,例如打印一系列点。自从输出被缓冲后,您应该会在 10 秒后立即看到所有输出:

        #!perl foreach ( 1 .. 10 ) { 打印 ”。”; 睡觉1; } 打印“\n”;

        现在,尝试设置$| 并使用system 调用它:

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

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

        【讨论】:

          猜你喜欢
          • 2013-06-25
          • 2010-11-28
          • 2021-11-24
          • 1970-01-01
          • 1970-01-01
          • 2011-05-23
          • 2014-08-16
          • 1970-01-01
          • 2017-03-15
          相关资源
          最近更新 更多