perlstdoutfilehandle

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.


Solution

  • 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."