Keith Bentrup
Keith Bentrup

Reputation: 11995

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 syntax doesn't work.

Upvotes: 9

Views: 6941

Answers (4)

Jonathan Leffler
Jonathan Leffler

Reputation: 755006

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.

Upvotes: 4

brian d foy
brian d foy

Reputation: 132920

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.

Upvotes: 3

FMc
FMc

Reputation: 42421

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.

Upvotes: 14

jheddings
jheddings

Reputation: 27573

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";

Upvotes: 6

Related Questions