in reply to Reopening STDOUT

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

Replies are listed 'Best First'.
Re^2: Reopening STDOUT ([open])
by tye (Sage) on Oct 10, 2003 at 20:45 UTC

    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?