如何在perl中重定向库函数的输出?

时间:2014-11-17 21:18:46

标签: perl redirect output

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

program.pl

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

xxLib1xx.pm

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

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

system("echo hello > nul");

4 个答案:

答案 0 :(得分:3)

查看Capture::Tiny

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

答案 1 :(得分:3)

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

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

答案 2 :(得分:0)

答案 3 :(得分:0)

在shooper回复的帮助下回答:

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