Alex Rivera | Logout

How Do I Point a File Handle to STDOUT (or Another File Handle) In Perl?

Asked 2011-06-09T17:00:09.137
27

I want to make a quick script that writes to a file if a file is given, or stdout if no file is given. It would be much easier for me to do this if I could start the script by pointing a new file handle, OUTFILE, to whichever of these is appropriate.

I know I can accomplish what I want by just pointing STDOUT to my output file when appropriate, but I'd rather not do that as I don't want to confuse anyone using the script later and wondering why their print statements don't work. Also, I'd still like to use the occasional print statement myself for troubleshooting purposes, and never want this print to the output file.

All of this said, what I'm looking for is something along the lines of:
open( OUTFILE, ($output ? ">$output" : STDOUT );
except that doesn't work.

Ideas?

Edit
Report

1 Answer

38

Some ways (globs):

# Requires 2-arg open, unfortunately
open(OUTPUT, "> ".($output || '-'))  or die;

if ($output) {
   open(OUTPUT, '>', $output) or die;
} else {
   *OUTPUT = *STDOUT;
}

if ($output) {
   open(OUTPUT, '>', $output) or die;
} else {
   open(OUTPUT, '>&', \*STDOUT) or die;
}

Some ways (lexical var):

# Requires 2-arg open, unfortunately
open(my $fh, "> ".($output || '-'))  or die;

my $fh;
if ($output) {
   open($fh, '>', $output) or die;
} else {
   $fh = \*STDOUT;
}

my $fh;
if ($output) {
   open($fh, '>', $output) or die;
} else {
   open($fh, '>&', \*STDOUT) or die;
}

Some ways (other):

# Changes the default handle for <print "foo">.
if ($output) {
   open(OUTPUT, '>', $output) or die;
   select(OUTPUT);
}
answered 2011-06-09T18:33:03.993

Your Answer