是否可以从Perl的需要中捕获输出?
例如:
{
local @ARGV = qw/ hello world /;
require 'myscript.pl';
}
我想捕获myscript.pl
生成的任何标准输出。可以想象这样的事情:
{
local @ARGV = qw/ hello world /;
my $output = require 'myscript.pl';
}
答案 0 :(得分:3)
Capture::Tiny让这更容易:
use Capture::Tiny 'capture_stdout';
my $output = capture_stdout {
local @ARGV = qw/hello world/;
require 'foo.pl';
};
虽然我同意这通常不是运行脚本的好方法。
答案 1 :(得分:2)
是的,这是可能的。您需要在STDOUT
之前重定向require
,然后恢复原始STDOUT
。
a.pl
my $capture;
open STDOUTBACKUP, '>&STDOUT';
close STDOUT;
open STDOUT, '>', \$capture;
require 'b.pl';
close STDOUT;
open STDOUT, '>&STDOUTBACKUP';
print "CAPTURED: $capture";
b.pl
print "ModuleB";
输出为CAPTURED: ModuleB
答案 2 :(得分:0)
myscript.pl
似乎是一个Perl脚本。使用require
或do
use String::ShellQuote qw( shell_quote );
my $cmd = shell_quote('myscript.pl', 'hello', 'world');
my $output = `$cmd`;
die("Can't execute myscript.pl: $!\n") if $? == -1;
die("myscript.pl killed by signal ".( $? & 0x7F )."\n") if $? & 0x7F;
die("myscript.pl returned error ".( $? >> 8 )."\n") if $? >> 8;
或
open(my $pipe, '-|', 'myscript.pl', 'hello', 'world')
or die("Can't execute myscript.pl: $!\n");
my $output = '';
$output .= $_ while <$pipe>;
close($pipe);
die("myscript.pl killed by signal ".( $? & 0x7F )."\n") if $? & 0x7F;
die("myscript.pl returned error ".( $? >> 8 )."\n") if $? >> 8;