Redirect stdout to a variable while requiring other script

谁说胖子不能爱 提交于 2019-12-12 03:37:57

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!