in reply to Opening and Closing STDOUT

localize the typeglob *STDOUT that contains the STDOUT filehandle within a block, then call your chatty code within the block:

{ local *STDOUT; # call something that prints to STDOUT }

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

    ++chromatic , certainly localizing *STDOUT fixes the problem, but just to play devils advocate..., IS it possible to close STDOUT and re-open it again to the console?

    print "Standard and Out\n"; close STDOUT; open (STDOUT, ">>over.txt") or die "Screaming $!"; print "Over and Out\n"; close STDOUT; open (STDOUT, ">>/dev/pts/0") or die "Can open console $!" #Ok so I ch +eated and used `who` to find this print "Aye Aye Capt'n\n";

    Which of course is largely useless and redundant given your solution, plus I have NFI how to programatically determine which /dev to open


    food for thought gives me indigestion

      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.

        ++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