[英]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.