Grayson Henry
Grayson Henry

Reputation: 862

How to redirect output from a Library's function in perl?

I am trying to redirect the output from a library's function without changing the code in the library:

program.pl

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

xxLib1xx.pm

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

How can I modify the code in program.pl so the when I call Function1, no output is seen? I cannot change the code in the Library itself. If I did a system call, it would look like:

system("echo hello > nul");

Upvotes: 2

Views: 732

Answers (4)

Grayson Henry
Grayson Henry

Reputation: 862

Answered with help from shooper's response:

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

Upvotes: 0

shooper
shooper

Reputation: 626

This is answered well at http://perltricks.com/article/45/2013/10/27/How-to-redirect-and-restore-STDOUT

Hope that helps.

Upvotes: -1

AKHolland
AKHolland

Reputation: 4445

And an answer without using CPAN modules can still be pretty compact:

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

Upvotes: 4

Diab Jerius
Diab Jerius

Reputation: 2320

Check out Capture::Tiny

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

Upvotes: 3

Related Questions