Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open filehandle or assign stdout

I'm working in a program where the user can pass a -o file option, and output should be then directed to that file. Otherwise, it should go to stdout.

To retrieve the option I'm using the module getopt long, and that's not the problem. The problem is that I want to create a file handle with that file or assign stdout to it if the option was not set.

if ($opt) {
    open OUTPUT, ">", $file;
} else {
    open OUTPUT, # ???
}

That's because this way, later in my code I can just:

print OUTPUT "...";

Without worrying if OUTPUT is stdout or a file the user specified. Is this possible? If I'm doing a bad design here, please let me know.

like image 810
cmre Avatar asked Aug 14 '11 19:08

cmre


2 Answers

This would be a good example on how to use select.

use strict;
use warnings;
use autodie;

my $fh;
if ($opt) {
    open $fh, '>', $file;
    select $fh;
}

print "This goes to the file if $opt is defined, otherwise to STDOUT."
like image 166
TLP Avatar answered Oct 19 '22 11:10

TLP


Look at the open documentation. The easiest is to reopen STDOUT itself and not use a filehandle in your code.

if ($opt) {
    open(STDOUT, ">", $file);
}
...

print "this goes to $file or STDOUT\n";

(Add some error checking of course.)

like image 44
Mat Avatar answered Oct 19 '22 11:10

Mat