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.
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!"
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With