开发者

How do I toggle printing to STDOUT/STDERR dynamically in Perl?

I'm curious if I can toggle between printing to STDOUT or STDERR based on some value or inline expression (without using an if statement).

print ($someFlag ? STDOUT : STDERR) "hello world!"

Obviously, that syn开发者_StackOverflowtax doesn't work.


I think this will do what you want:

print {$someFlag ? *STDOUT : *STDERR} "hello world!";

A similar example can be seen in the documentation for print. Use typeglobs so that it will run under use strict.

Another strategy is to define your own printing function that will behave differently, depending on the value of $someFlag.


Do you need to evaluate for each call to print?

If not, would this work for you:

my $redir = $someFlag ? STDOUT : STDERR;
print $redir "hello world!\n";


One mechanism is to 'select' the output descriptor (file channel).

select STDERR;
print ...goes to STDERR...;
select STDOUT;
print ...goes to STDOUT...;

I suspect this is now deprecated, though.


I wrap this sort of thing in a method that returns the appropriate filehandle:

 print { $obj->which_handle_do_I_want } "Some message";

You might want to look at how IO::Interactive.

However, if you're doing this for logging, I recommend Log::Log4perl since you can not only change where the output goes, but can send the output to multiple places, set priorities for the message, and a lot more. And, you can change all of that without changing the source.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜