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

Is this a valid code snippet?

if ( "true" == $flag ) { open ( OUT, "output.txt" ) or die ( "could not open output.txt: $!" +); } else { <OUT> = <STDOUT>; } print OUT "If $flag is true, this line will go to the file output.txt\ +nIf $flag is false, it will go to standard output\n";

If that code is not right, can someone tell me how to do something in that spirit (read the print statement for what I want it to do).

Thanks in advance,

JAPH

Replies are listed 'Best First'.
Re: can you assign file handles?
by chromatic (Archbishop) on Jan 30, 2001 at 03:11 UTC
    It's invalid, because the <FILEHANDLE> construct reads a line from the filehandle. It doesn't refer to a filehandle in general.

    If you want to copy a filehandle, you can simply say *OUT = *STDOUT.

    You can also use the dup-version of open to get a new file descriptor to the same file. That's probably not what you want.

    If you're doing what I think you're doing, use select to select OUT for output, then print as normal.

Re: can you assign file handles?
by Fastolfe (Vicar) on Jan 30, 2001 at 03:25 UTC
    Note that "-" is a valid filename for use with open, and is equivalent to opening STDOUT (or STDIN, depending upon how you use it). You might work that into your logic.
    open(OUT, $flag ? ">>output.txt" : ">>-") or die "...";
Re: can you assign file handles?
by runrig (Abbot) on Jan 30, 2001 at 03:29 UTC
    And once again, we have '==' where we meant to use 'eq' :-)
Re: can you assign file handles?
by hotyopa (Scribe) on Jan 30, 2001 at 03:11 UTC
    I think that the following would achieve what you require:
    if ("true" eq $flag) { open (OUT, ">output.txt") or die ("could not open output.txt: $!") +; } else { open (OUT, ">&STDOUT"); }

    Update:Changed as per bbfu's comment below, although I kept the duplication because IMHO it makes it easier for a newbie to follow.

    *~-}hotyopa{-~*

      Whoa... Actually, you would need

      if ("true" eq $flag) {

      or

      if ($flag) {

      as the condtion of the if statement (I'm still not sure if they wanted to actually test for boolean truth or equality to the string "true"). Assignment's right out.

      But the reopening of OUT is definately what they wanted! =) (Though I think I, personally, actually prefer Fastolfe's method of using the trinary operator and one open statement so as not to duplicate code and so you test the dup-open for success as well. TIMTOWTDI. =)

      bbfu