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

I know you can suppress printed messages by saying,
open STDOUT, '>/dev/null';
but is there anyway to REopen it so you can receive messages again?

Replies are listed 'Best First'.
Re: Reopening STDOUT
by Zaxo (Archbishop) on Oct 10, 2003 at 20:21 UTC

    There are several ways to do this.

    1. My favorite, localize STDOUT in a block,

    { open local(*STDOUT), '>', '/dev/null' or die $!; #... close STDOUT or die $!; } # STDOUT is restored here

    2. Open a different filehandle and select it to be the default output filehandle,

    open NIL, '>', '/dev/null' or die $!; select NIL; #... select STDOUT; close NIL or die $!;

    3. Duplicate STDOUT to some other handle *OLDSO, open STDOUT, print things, close STDOUT, duplicate *OLDSO to STDOUT, close *OLDSO. I don't like this one, too fussy.

    After Compline,
    Zaxo

      Your favorite trick can break some things. I just avoid copying or localizing globs that contain open file handles as I find there are too many egde cases where things break.

      I much prefer to use the technique documented directly in the open documentation. Here is a modified version of it that doesn't bother with STDERR:

      open( OLDOUT, ">&STDOUT" ); open( STDOUT, '> foo.out' ) or die "Can't redirect STDOUT to foo.out: $!\n"; # this works for subprocesses and C code too: print "stdout 1\n"; close( STDOUT ); open( STDOUT, ">&OLDOUT" ); close( OLDOUT );
      You can use a non-bareword file handle in place of OLDOUT, if you prefer.

                      - tye
        ...as I find there are too many egde cases where things break.

        Such as?

Re: Reopening STDOUT
by hardburn (Abbot) on Oct 10, 2003 at 20:15 UTC

    You can open a new filehandle, select() it, and then reselect the old one:

    open NEW_STDOUT, '>/dev/null' or die $!; select(NEW_STDOUT); print "Won't be printed\n"; select(STDOUT); close(NEW_STDOUT); print "Printing again\n";

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    Note: All code is untested, unless otherwise stated