3

我想command使用 perl 运行一些命令(例如)system()。假设command像这样从 shell 运行:

command --arg1=arg1 --arg2=arg2 -arg3 -arg4

我如何使用这些参数system()运行?command

4

4 回答 4

9

最佳实践:避免使用 shell,使用自动错误处理 - 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's answer包括指向系统文档的链接。在那里,我们可以看到每次都需要包含一段代码才能system正确执行。eugene y 的回答显示了其中的一部分。

每当我们遇到这种情况时,我们都会将重复的代码捆绑在一个模块中。我将与适当的简洁异常处理相提并论Try::Tiny,但是正确IPC::System::Simple的做法并没有看到社区的这种快速采用。似乎需要更频繁地重复。system

所以,使用autodie!使用IPC::System::Simple省去自己的乏味,请确保您使用经过测试的代码。

于 2010-08-13T14:55:23.613 回答
5
my @args = qw(command --arg1=arg1 --arg2=arg2 -arg3 -arg4);
system(@args) == 0 or die "system @args failed: $?";

更多信息在perldoc中。

于 2010-08-13T14:44:58.953 回答
1

与 Perl 中的所有内容一样,有不止一种方法可以做到这一点 :)

最好的方法,将参数作为列表传递:

system("command", "--arg1=arg1","--arg2=arg2","-arg3","-arg4");

尽管有时程序似乎与该版本不兼容(特别是如果它们希望从 shell 调用)。如果您将其作为单个字符串执行,Perl 将从 shell 调用该命令。

system("command --arg1=arg1 --arg2=arg2 -arg3 -arg4");

但是这种形式比较慢。

于 2010-08-13T14:45:13.827 回答
1
my @args = ( "command", "--arg1=arg1", "--arg2=arg2", "-arg3", "-arg4" );
system(@args);
于 2010-08-13T14:50:33.030 回答