This is ... not possible.
Standard output of piped opens and system
calls are written to file descriptor 1. Normally, Perl's STDOUT
file handle is associated with file descriptor 1, but that can be manipulated.
In this example, the system
calls writes to STDOUT
filehandle, which writes to the file foo
.
close STDOUT; # closes file descriptor 1
open STDOUT, '>', 'foo'; # reopens STDOUT as file descriptor 1
system("echo bar");
close STDOUT;
print STDERR "foo: ",`cat foo`;
# result: "foo: bar"
But in this example, the system
calls writes to the BAZ
filehandle.
close STDOUT; # closes file descriptor 1
open BAZ, '>', 'baz'; # attaches fd 1 to handle BAZ
open STDOUT, '>', 'foo'; # opens new file descriptor, maybe fd 3
system("echo bar");
close STDOUT;
print STDERR "foo: ",`cat foo`;
print STDERR "baz: ",`cat baz`;
# result: "foo: baz: bar"
An in-memory filehandle is not a real filehandle. If you call fileno
on it, you will (generally, may be OS dependent) get a negative number.
open STDOUT, '>', $scalar;
print STDERR fileno(STDOUT); # -1
Piped opens and system calls will not be able to write to this filehandle.
You will need a more complicated workaround, like writing the piped open output to a file, and then copying that file into the in-memory variable.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…