Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to capture a subroutine's print output to a variable so I can send it to stderr instead?

Tags:

stderr

perl

Suppose we have:

sub test {
        print "testing\n";
}

If there is a case where I want to have it print to stderr instead of stdout, is there a way I can call the subroutine to do this? Or can I capture the output to a variable and then use warn? I'm fairly new to perl.

like image 933
gravitas Avatar asked May 17 '13 18:05

gravitas


People also ask

How do I print to stderr in Perl?

And similarly, how to print the line to STDERR? In Perl, to nicely print a new line to STDOUT, you can use the “say” feature which “Just like print, but implicitly appends a newline”: use 5. 010; say "hello world!"


1 Answers

Yes there is. print sends its output to the "selected" filehandle, which is usually STDOUT. But Perl provides the select function for you to change it.

select(STDERR);
&test;           # send output to STDERR
select(STDOUT);  # restore default output handle

The select function returns the previously selected filehandle, so you can capture it and restore it later.

my $orig_select = select(STDERR);
&test;
select($orig_select);
like image 177
mob Avatar answered Sep 21 '22 13:09

mob