我想使用Perl的system()
运行一些命令(例如command
)。假设command
是从shell中这样运行的:
command --arg1=arg1 --arg2=arg2 -arg3 -arg4
我该如何使用system()
函数来运行带有这些参数的command
命令?
IPC::System::Simple
。require IPC::System::Simple;
use autodie qw(:all);
system qw(command --arg1=arg1 --arg2=arg2 -arg3 -arg4);
use IPC::System::Simple qw(runx);
runx [0], qw(command --arg1=arg1 --arg2=arg2 -arg3 -arg4);
# ↑ list of allowed EXIT_VALs, see documentation
编辑:接下来是一段发泄。
eugene y的回答包含了一个指向system文档的链接。在那里,我们可以看到需要每次包含一个庞大的代码块才能正确执行system
。eugene y的回答只展示出其中的一部分。
每当我们遇到这种情况时,我们都会将重复的代码捆绑在一个模块中。我将其与使用Try::Tiny
进行适当无花费异常处理进行类比,然而被称为正确的system
的IPC::System::Simple
并没有得到社区的快速采用。似乎需要更多的重复。
所以,使用autodie
!使用IPC::System::Simple
!省去烦琐,确保使用经过测试的代码。
my @args = qw(command --arg1=arg1 --arg2=arg2 -arg3 -arg4);
system(@args) == 0 or die "system @args failed: $?";
More information is in perldoc.
就像 Perl 中的所有事情一样,有不止一种方法来完成它 :)
最好的方法是将参数作为列表传递:
system("command", "--arg1=arg1","--arg2=arg2","-arg3","-arg4");
尽管有时候程序似乎不能完全兼容该版本(特别是如果它们期望从 shell 调用)。如果您将其作为单个字符串执行,Perl 将会从 shell 调用该命令。
system("command --arg1=arg1 --arg2=arg2 -arg3 -arg4");
但是那种形式比较慢。
my @args = ( "command", "--arg1=arg1", "--arg2=arg2", "-arg3", "-arg4" );
system(@args);
$?
?我不这么认为。 - ysth