in reply to Re: How can I re-open STDOUT?
in thread How can I re-open STDOUT?
File descriptors change between opens and closes, but Perl tries to take care of STDERR, STDOUT, STDIN. Ok, not really - it only pays attention to file descriptors that are less than $^F - whose default is 2. So it all works out. Basically you could reopen STDOUT using open(FILEHANDLE, "<&=$fd") where $fd is the file descriptor number. It goes on to warn that these can change if you start opening and closing them all willy nilly.
Cheers - L~R
Update: Per broquaint's /msg to me, this doesn't work. I assumed when the documentation said Perl took special care to look out for certain file descriptors - it meant that it only made it look like you had closed them but it really did the "save so you could restore". Apparently not. After reading perldoc perlvar on $^F - Perl preserves these descriptors during open even in the event of a failure. As we all know - opening up the same filehandle normally closes the original. So if the open fails, you still have STDOUT, and if the open succedes the new handle gets the old descriptor number.
Update 2: As broquaint and I argued about this for quite some time in the CB, I am going to provide code to illustrate that the docs are right - even though they are misleading. The Camel is even more misleading IMO.
Now notice what happens with close#!/usr/bin/perl -w use strict; print "foo bar\n"; # Goes to screen open (STDOUT, ">my_log") or die $!; print "foo bar\n"; # Goes to Log open (STDOUT,">&=1") or die $!; print "foo bar\n"; # Hoped it went to screen, but goes to log
Ok - what happens if the open fails and you don't say or die?#!/usr/bin/perl -w use strict; print "foo bar\n"; # Goes to screen open (STDOUT, ">my_log") or die $!; print "foo bar\n"; # Goes to Log close STDOUT; # Gone forever open (STDOUT,">&=1") or die $!; # death - goodbye cruel world
#!/usr/bin/perl -w use strict; print "foo bar\n"; # Goes to screen open (STDOUT, ">/my_log"); # Don't have write permission to / print "foo bar\n"; # Goes to screen since it is preserved
|
|---|