【问题标题】:How to redirect output from a Library's function in perl?如何在perl中重定向库函数的输出?
【发布时间】:2014-11-18 08:16:19
【问题描述】:

我正在尝试重定向库函数的输出而不更改库中的代码:

程序.pl

use Lib::xxLib1xx;
...
xxLib1xx::Function1($Arg1);

xxLib1xx.pm

Function1{
    my $arg = shift;
    print "$arg\n";
}

如何修改 program.pl 中的代码,以便在调用 Function1 时看不到任何输出?我无法更改库本身的代码。 如果我进行系统调用,它看起来像:

system("echo hello > nul");

【问题讨论】:

标签: perl redirect output


【解决方案1】:

不使用 CPAN 模块的答案仍然可以非常紧凑:

my $stdout;
{
    local *STDOUT;
    open STDOUT, ">", \$stdout;
    xxLib1xx::Function1($Arg1);
}
print "Got '$stdout' from subroutine call!\n";

【讨论】:

    【解决方案2】:

    查看Capture::Tiny

    use Capture::Tiny qw[ capture ];
    ( $stdout, $stderr, @result) = capture { xxLib1xx::Function1($Arg1) };
    

    【讨论】:

      【解决方案3】:

      在购物者回复的帮助下回答:

      my $LOG;
      open ($LOG, '>>', 'null');
      select $LOG;
      ...
      xxLib1xx::Function1($Arg1);
      ...
      select STDOUT;
      

      【讨论】:

        【解决方案4】:

        这在http://perltricks.com/article/45/2013/10/27/How-to-redirect-and-restore-STDOUT得到了很好的回答

        希望对您有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-04-25
          • 2012-12-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多