问题
I'm trying to redirect STDOUT to a variable, which seems to work fine. However, when I'm requiring other script, its expected output is not stored in that variable.
my $var;
#save STDOUT for future redirect
open OLDOUT, '>&STDOUT';
close STDOUT;
# redirect STDOUT to $var
open STDOUT, '>', \$var or die "Can't open STDOUT: $!";
# run the script that I'm supposed to catch its output
do("macro.pl");
close STDOUT;
# redirect STDOUT to its original FH
open STDOUT, '>&OLDOUT' or die "Can't restore stdout: $!";
close OLDOUT or die "Can't close OLDOUT: $!";
# print the expected result from macro.pl
print "$var";
The last line prints nothing, which is not the expected result (running macro.pl alone yields a non-empty output).
Tried it also with require - same result. It is worth mentioning that macro.pl doesn't - in any way - changes the standard file descriptors.
Thanks!
回答1:
You need to select the filehandle in order to make it the default filehandle (aka STDOUT). Try it like this.
my $printBuffer; # Your output will go in here
open(my $buffer, '>', \$printBuffer);
my $stdout = select($buffer); # $stdout is the original STDOUT
do 'macro.pl';
select($stdout); # go back to the original
close($buffer);
print $printBuffer;
来源:https://stackoverflow.com/questions/14234733/redirect-stdout-to-a-variable-while-requiring-other-script