[英]Why IPC::System::Simple(capture) is not working with arguments
我正在尝试从主脚本中调用第二个脚本。 当我使用捕获在命令本身中传递参数时,它正在工作。 但是,当我尝试在捕获 function 中分别发送命令和 arguments 时,它给我一个错误,它找不到指定的文件。
第二个脚本
#!/usr/bin/perl
use 5.010;
use strict;
use warnings;
my $word= $ARGV[0];
my $crpyt = "$word crypted";
print "$crpyt\n";
my $decrypt = "$word decrypted";
print "$decrypt\n";
主文件
#!/usr/bin/perl
use 5.010;
use strict;
use warnings;
use IPC::System::Simple qw(capture capturex);
my $cmd= 'perl xyz.pl Hello';
my @arr = capture($cmd);
print "$arr[0]";
print "$arr[1]\n";
这是工作Output:
Hello crypted
Hello decrypted
但是main.pl
#!/usr/bin/perl
use 5.010;
use strict;
use warnings;
use IPC::System::Simple qw(capture capturex);
my $cmd= 'perl xyz.pl';
my @arg=("Hello");
my @arr = capture($cmd,@arg);
print "$arr[0]";
print "$arr[1]\n";
这是行不通的。 它说"perl xyz.pl" failed to start: "The system cannot find the file specified" at main.pl line 11
如果您只传递一个标量,则capture
预计它是 shell 命令。
因此, capture('perl xyz.pl Hello')
有效。
如果您传递多个标量,则capture
期望第一个是要执行的程序的路径。 rest 作为 arguments 传递。
因此, capture('perl xyz.pl', 'Hello')
不起作用。
你可以使用
use IPC::System::Simple qw( capture );
my @cmd = ( 'perl', 'xyz.pl', 'Hello' );
capture(@cmd)
但是你永远不想使用capture
,除非你传递一个单一的标量,即 shell 命令。 传递路径和capturex
时使用 capturex。
use IPC::System::Simple qw( capturex );
my @cmd = ( 'perl', 'xyz.pl', 'Hello' );
capturex(@cmd)
但是,假设您从其他地方获得字符串perl xyz.pl
需要调用 shell,因此我们需要将 arguments 转换为 shell 文字。
use IPC::System::Simple qw( capture );
use String::ShellQuote qw( shell_quote );
my $cmd = 'perl xyz.pl';
my @extra_args = 'Hello';
my $full_cmd = $cmd . ' ' . shell_quote(@extra_args);
capture($cmd)
或者,
use IPC::System::Simple qw( capturex );
my $cmd = 'perl xyz.pl';
my @extra_args = 'Hello';
capturex('sh', '-c', 'eval $0 "$@"', $cmd, @extra_args)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.