使用Perl的`system`函数

3

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

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

我该如何使用system()函数来运行带有这些参数的command命令?

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的回答包含了一个指向system文档的链接。在那里,我们可以看到需要每次包含一个庞大的代码块才能正确执行system。eugene y的回答只展示出其中的一部分。

每当我们遇到这种情况时,我们都会将重复的代码捆绑在一个模块中。我将其与使用Try::Tiny进行适当无花费异常处理进行类比,然而被称为正确的systemIPC::System::Simple并没有得到社区的快速采用。似乎需要更多的重复。

所以,使用autodie!使用IPC::System::Simple省去烦琐,确保使用经过测试的代码。


2
要想"正确地"执行系统命令,你必须解码$??我不这么认为。 - ysth
我很惊讶,您这样专业的人居然不知道它确实需要解码。 - daxim
3
你可能只关心"零"和"非零"的概念,对其他事情并不在意。 - hobbs

5
my @args = qw(command --arg1=arg1 --arg2=arg2 -arg3 -arg4);
system(@args) == 0 or die "system @args failed: $?";

More information is in perldoc.


1

就像 Perl 中的所有事情一样,有不止一种方法来完成它 :)

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

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

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

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

但是那种形式比较慢。


2
使用字符串或数组作为system函数的参数,速度并不是问题:http://perldoc.perl.org/functions/system.html - Sinan Ünür

1
my @args = ( "command", "--arg1=arg1", "--arg2=arg2", "-arg3", "-arg4" );
system(@args);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接