File handles opened using open FILE, ">", \$var don't have file descriptors since there are no corresponding OS file handles. Since open FILE2, ">&FILE" means open a new file from the file descriptor of "FILE", it's no suprise it doesn't work. The code below demonstrates this and a fix.
#!/usr/bin/perl -w use strict; use FileHandle; printf("fileno(*STDOUT) = %d\n", fileno(*STDOUT)); # 1 printf("fileno(*STDERR) = %d\n", fileno(*STDERR)); # 2 open SAVED_STDOUT, ">&STDOUT" or die "couldn't save STDOUT: $!\n"; open SAVED_STDERR, ">&STDERR" or die "couldn't save STDERR: $!\n"; print SAVED_STDOUT ""; # to suppress warning about possible typo print SAVED_STDERR ""; # to suppress warning about possible typo my $captured_output = ""; close STDOUT; open STDOUT, ">", \$captured_output or die "couldn't re-open STDOUT: $!\n"; close STDERR; #open STDERR, ">&STDOUT" or die "couldn't re-open STDERR: $!\n"; *STDERR = *STDOUT; printf SAVED_STDOUT ("fileno(*STDOUT) = %d\n", fileno(*STDOUT)); # -1 printf SAVED_STDOUT ("fileno(*STDERR) = %d\n", fileno(*STDERR)); # -1 print "testing stdout capture 1\n"; print STDERR "testing stderr capture\n"; print "testing stdout capture 2\n"; close STDOUT; open STDOUT, ">&SAVED_STDOUT"; close STDERR; open STDERR, ">&SAVED_STDERR"; print $captured_output, "\n";
You could simplify the above code to:
#!/usr/bin/perl -w use strict; my $captured_output = ""; { local *STDOUT; open STDOUT, ">", \$captured_output or die "couldn't re-open STDOUT: $!\n"; local *STDERR = *STDOUT; print "testing stdout capture 1\n"; print STDERR "testing stderr capture\n"; print "testing stdout capture 2\n"; } print $captured_output, "\n";
In reply to Re: possible bug in opening file handle to variable
by ikegami
in thread possible bug in opening file handle to variable
by youngh
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |