loris has asked for the wisdom of the Perl Monks concerning the following question:

Monks,

I'm sure I should know how to do this: if an output file name is defined, write output to that file, otherwise to STDOUT, i.e.

if ($outfile) { open($out, ">", $outfile); } else { $out = ??? } print $out $text;

What do I need in the else branch?

Thanks, loris

Update: Just fixed typo in title.

Replies are listed 'Best First'.
Re: Swiching between output to file and STDOUT
by davorg (Chancellor) on Nov 09, 2004 at 13:58 UTC
    if (defined $outfile) { open OUTPUT, '>', $outfile; select OUTPUT; } # then just use "print"

    Update: Fletch is right. I've removed the misleading reference to STDOUT.

    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

      And by "then just print to STDOUT" he means "just print without specifying a filehandle" (e.g. print "foo\n").

      Even if you change the default output handle with select OUTPUT the statement print STDOUT "foo" will still print to stdout.

Re: Swiching between output to file and STDOUT
by borisz (Canon) on Nov 09, 2004 at 14:00 UTC
Re: Swiching between output to file and STDOUT
by thor (Priest) on Nov 09, 2004 at 20:43 UTC
    I was going to reply with the special file "-" (as documented in perlopentut), but I found an inconsistency between 2-arg and 3-arg open. If I do this
    open(OUTPUT, '>-') or die; print OUTPUT "foo\n";
    I get "foo\n" on standard out. However, if I use 3-arg open like so:
    open(OUTPUT, ">", '-') print "foo\n";
    I get the output directed to a file called '-'. This seems like it might be a bug...can anyone point me to somewhere in the docs where this is documented behavior?

    thor

    Feel the white light, the light within
    Be your own disciple, fan the sparks of will
    For all of us waiting, your kingdom will come

      This seems like it might be a bug...can anyone point me to somewhere in the docs where this is documented behavior?

      Certainly. perldoc open (at least, my local pod) states:

      In the 2-arguments (and 1-argument) form opening '-' opens STDIN and opening '>-' opens STDOUT.

      It specifically declines to mention 3-arg open.

      --
      edan

      It isn't a bug. 3-arg open is the magicless form of the call, and is exactly what you should use when you *do* want to open a file named "-". It's a bit safer in other places too, because it doesn't make pipes of '|' characters. "../" still goes up a dir, though.
Re: Swiching between output to file and STDOUT
by saintmike (Vicar) on Nov 09, 2004 at 21:10 UTC
    Since what you're doing looks like logging, why not go full throttle and use Log::Log4perl:
    my $outfile; use Log::Log4perl qw(:easy); Log::Log4perl->easy_init( {level => $DEBUG, file => (defined $outfile ? $outfile : "STDOUT")}); DEBUG "hey!";