Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 795
Keith Bentrup Avatar asked Nov 21 '09 22:11

Keith Bentrup


2 Answers

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.

like image 130
FMc Avatar answered Sep 19 '22 12:09

FMc


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";
like image 42
jheddings Avatar answered Sep 17 '22 12:09

jheddings