在需要其他脚本时将标准输出重定向到变量
我正在尝试将 STDOUT 重定向到一个变量,这似乎工作正常.但是,当我需要其他脚本时,其预期输出不会存储在该变量中.
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";
最后一行不打印任何内容,这不是预期的结果(单独运行 macro.pl 会产生非空输出).
The last line prints nothing, which is not the expected result (running macro.pl alone yields a non-empty output).
也用 require 尝试过 - 结果相同.值得一提的是,macro.pl 不会——以任何方式——改变标准文件描述符.
Tried it also with require - same result. It is worth mentioning that macro.pl doesn't - in any way - changes the standard file descriptors.
谢谢!
您需要选择
文件句柄以使其成为默认文件句柄(又名STDOUT
).像这样试试.
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;