在需要其他脚本时将标准输出重定向到变量 [英] Redirect stdout to a variable while requiring other script

查看:40
本文介绍了在需要其他脚本时将标准输出重定向到变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 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;

这篇关于在需要其他脚本时将标准输出重定向到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆