以下假设 @cmd 包含程序及其参数(如果有)。
my @cmd = ('foo');
如果要捕获输出,可以使用以下任意一种:
use String::ShellQuote qw( shell_quote );
my $cmd1 = shell_quote('printf', '%s', $_);
my $cmd2 = shell_quote(@cmd);
my $output = qx{$cmd1 | $cmd2};
use IPC::Run3 qw( run3 );
run3(\@cmd, \$_, \my $output);
use IPC::Run qw( run );
run(\@cmd, \$_, \my $output);
如果您不想捕获输出,可以使用以下任何一种:
use String::ShellQuote qw( shell_quote );
my $cmd1 = shell_quote('printf', '%s', $_);
my $cmd2 = shell_quote(@cmd);
system("$cmd1 | $cmd2");
system('/bin/sh', '-c', 'printf "%s" "$0" | "$@"', $_, @cmd);
use String::ShellQuote qw( shell_quote );
my $cmd = shell_quote(@cmd);
open(my $pipe, '|-', $cmd);
print($pipe $_);
close($pipe);
open(my $pipe, '|-', '/bin/sh', '-c', '"$@"', 'dummy', @cmd);
print($pipe $_);
close($pipe);
use IPC::Run3 qw( run3 );
run3(\@cmd, \$_);
use IPC::Run qw( run );
run(\@cmd, \$_);
如果您不想捕获输出,但也不想看到它,您可以使用以下任何一种:
use String::ShellQuote qw( shell_quote );
my $cmd1 = shell_quote('printf', '%s', $_);
my $cmd2 = shell_quote(@cmd);
system("$cmd1 | $cmd2 >/dev/null");
system('/bin/sh', '-c', 'printf "%s" "$0" | "$@" >/dev/null', $_, @cmd);
use String::ShellQuote qw( shell_quote );
my $cmd = shell_quote(@cmd);
open(my $pipe, '|-', "$cmd >/dev/null");
print($pipe $_);
close($pipe);
open(my $pipe, '|-', '/bin/sh', '-c', '"$@" >/dev/null', 'dummy', @cmd);
print($pipe $_);
close($pipe);
use IPC::Run3 qw( run3 );
run3(\@cmd, \$_, \undef);
use IPC::Run qw( run );
run(\@cmd, \$_, \undef);
注意事项:
使用printf 的解决方案将对传递给程序的STDIN 的数据大小施加限制。
使用printf 的解决方案无法将 NUL 传递给程序的 STDIN。
使用 IPC::Run3 和 IPC::Run 的解决方案不涉及 shell。这样可以避免问题。
-
您可能应该使用来自 IPC::System::Simple 的 system 和 capture 而不是内置的 system 和 qx 来获得“免费”错误检查。
李>