当前perl解释器的位置可以在特殊变量$^X
中找到。如果perl不在你的路径中,或者你有多个perl版本可用,但确保你在全局使用同一个版本,这是很重要的。
执行外部命令(包括其他Perl程序)时,确定它们是否真正运行可能会非常困难。检查$?
可以留下持久的心理伤痕,所以我更喜欢使用IPC::System::Simple(可从CPAN):
use strict;
use warnings;
use IPC::System::Simple qw(system capture);
# Run a command, wait until it finishes, and make sure it works.
# Output from this program goes directly to STDOUT, and it can take input
# from your STDIN if required.
system($^X, "yourscript.pl", @ARGS);
# Run a command, wait until it finishes, and make sure it works.
# The output of this command is captured into $results.
my $results = capture($^X, "yourscript.pl", @ARGS);
在上面的两个例子,你想传递到外部程序的任何参数进入@ARGS
。在上述两个例子中都避免使用shell,这可以让您获得小的速度优势,并避免涉及shell元字符的任何不需要的交互。上面的代码也期望你的第二个程序返回一个零退出值来表示成功;如果你有一个长期运行的过程中,你要处理的数据而真实生成它
# Both of these commands allow an exit value of 0, 1 or 2 to be considered
# a successful execution of the command.
system([0,1,2], $^X, "yourscript.pl", @ARGS);
# OR
capture([0,1,2, $^X, "yourscript.pl", @ARGS);
,那么你”:如果不是这种情况,你可以指定允许出口值额外的第一个参数可能需要管道打开,或者CPAN中更重量级的IPC模块之一。尽管如此,无论何时您需要从Perl调用另一个Perl程序,您都可以考虑使用模块是否是更好的选择。从启动成本和流程间数据移动的I/O成本来看,启动另一个程序会带来相当多的开销。这也显着增加了错误处理的难度。如果您可以将外部程序转换为模块,则可能会发现它简化了整体设计。
一切顺利,
保罗
来源
2008-12-13 13:21:28
pjf
简单地使用'do'会不会更容易和更简洁? – innaM 2008-12-13 12:37:23
谢谢。我在列表中添加了'do'。 – Colin 2008-12-14 20:28:47