in reply to Re: Re: Opening and Closing STDOUT
in thread Opening and Closing STDOUT

Surely what you want to do is to duplicate the STDOUT file handle to keep it out of the way. Then duplicate it back to STDOUT when you are done. Something like:

local(*SAVED_STDOUT); open(SAVED_STDOUT,">&STDOUT"); ...Mess with STDOUT... close(STDOUT); open(STDOUT,">&SAVED_STDOUT");

Warning: I am not near a machine where I can check this at the moment, so this is probably not be accurate, look in your favourite O'Reilly book to get the real syntax.

Replies are listed 'Best First'.
Re:^4 Opening and Closing STDOUT
by submersible_toaster (Chaplain) on Mar 05, 2003 at 23:47 UTC

    ++hawtin , I think I shall need to cram on type_globs before I quite understand (/me attempts to de-dogear Perl-ina-Nutshell). Your code I think is correct, in syntax and function. This exhibits the right behaviour.

    #!/usr/bin/perl -w local (*SAVED_STDOUT); open (SAVED_STDOUT, ">&STDOUT"); print "Roo"; close STDOUT; open (STDOUT , ">>foo.bar") || die "$!"; print "s"; close STDOUT; open(STDOUT, ">&SAVED_STDOUT"); print "ters\n

    And of course the key here is RTFM (TOASTER!@) because perldoc -f open is insightful enough to provide....

    Here is a script that saves, redirects, and restores STDOUT and STDERR: #!/usr/bin/perl open(OLDOUT, ">&STDOUT"); open(OLDERR, ">&STDERR"); open(STDOUT, '>', "foo.out") || die "Can't redirect stdout"; open(STDERR, ">&STDOUT") || die "Can't dup stdout"; select(STDERR); $| = 1; # make unbuffered select(STDOUT); $| = 1; # make unbuffered print STDOUT "stdout 1\n"; # this works for print STDERR "stderr 1\n"; # subprocesses too close(STDOUT); close(STDERR); open(STDOUT, ">&OLDOUT"); open(STDERR, ">&OLDERR"); print STDOUT "stdout 2\n"; print STDERR "stderr 2\n";
    sweet.

    I can't believe it's not psellchecked