in reply to How do I restore STDOUT

Hey everyone-- There's nothing magical about SAVEOUT. I was trying to use Cookbook 7.20 to try a solution and picked an arbitrary filehandle (SAVEOUT) to test stuff out.

I've tried VSarkiss' idea already. The error messages were vague.

I then tried Brent's idea:

#!/usr/bin/perl -w $log_file = "logfile"; open(STDOUT, "| tee $log_file") or die "Can't open: $!\n"; print "Testing 1.2.3...\n"; close(STDOUT) or die "Can't close: $!\n"; open(STDOUT,'>-'); print "done\n"; close(STDOUT);
But that didn't work. I also tried ">-" but that didn't work either...In both cases, I never got "done" printed to the STDOUT. I stumbled upon this solution, though:
#!/usr/bin/perl -w $log_file = "logfile"; #copy file descriptor open(OLDOUT,">&STDOUT"); open(STDOUT, "| tee $log_file") or die "Can't open: $!\n"; print "Testing 1.2.3...\n"; close(STDOUT) or die "Can't close: $!\n"; #restore STDOUT open(STDOUT,">&OLDOUT"); print "done\n"; close(OLDOUT);
Results:
Testing 1.2.3... gets put into logfile and STDOUT done gets put on STDOUT only
Is there a less convoluted way of doing this without having to copy file descriptors? And why does this solution work...it still puzzles me why this works...I somehow got to this solution by reading 7.20.

Thanks everyone for your help. --slojuggler2

Replies are listed 'Best First'.
Re: Answer: How do I restore STDOUT
by Anonymous Monk on Jul 07, 2001 at 00:40 UTC
    That was meant by 'magical SAVOUT'. You must first copy your handle to another one to be able to copy back. In your first code you didn't do this and consequenly you copied a closed filehandle 'back'.