【问题标题】:Perl: What is the fastest way to run a perl script from within a perl script?Perl:从 perl 脚本中运行 perl 脚本的最快方法是什么?
【发布时间】:2014-01-29 19:42:06
【问题描述】:

我正在编写一个使用其他 Perl 脚本(不是我的)的 Perl 脚本。其中一些接收带有标志的输入,而另一些则没有。我需要的另一件事是将这些脚本的输出重定向到不同的文件。例如:

W\O flags: script1.pl arg1 arg2 arg3 > output1.log

W flags: script2.pl -a 1 -b 2 -c 3 > output2.log

底线 - 我使用 system() 来执行此操作,但后来我发现脚本花费的时间太长。 我尝试使用do() 执行此操作,但没有成功(例如here)。

那么最快的方法是什么?

【问题讨论】:

  • system 不会增加可测量的开销。你能更好地解释一下“最快”的方式是什么意思吗?
  • 在 perl 已经存在的任何地方使用 system() 不会减慢外部脚本的速度(除非您真的内存/文件描述符/等不足)足够快(即:未嵌入)。
  • 你想同时运行多个东西吗?
  • @Zaid,它不需要重新编译所有内容,因此可能需要几秒钟。
  • @user1953271、systemdo 不是一回事。你不能只用一个换另一个。事实上,do EXPR 没有任何意义。如果您想在与第一个相同的解释器中执行第二个脚本,请将其放入一个模块中。

标签: perl


【解决方案1】:

你需要让你的测试脚本定义一个子程序来执行你想要运行的所有东西,然后让你的主脚本读取测试脚本的 Perl 代码并调用该子程序——所以测试脚本看起来像这样:

#!/usr/bin/env perl
#
# defines how to run a test

use strict;
use warnings;

sub test
{
    my ($arg1, $arg2, $arg3) = @_;
    # run the test
    (...)
)

主脚本:

#!/usr/bin/env perl
#
# runs all of the tests

use strict;
use warnings;

require 'testdef.pl';  # the other script

foreach (...)
{
    (...)
    test($arg1, $arg2, $arg3);
}

这仍然是一种非常基本的方法。 正如ikegami所说,正确的方法是将测试脚本变成module。 如果您要创建比这两个更多的测试脚本文件,或者如果您想在不同的位置安装脚本,那将是值得的。

【讨论】:

    【解决方案2】:

    使用多参数系统调用:http://perldoc.perl.org/functions/system.html

    这不会执行 shell,你可以节省几个 CPU 周期

    system(qw(script1.pl arg1 arg2 arg3 > output1.log));
    

    "作为优化,可能不会调用指定的命令shell $ENV{PERL5SHELL} 。 system(1, @args) 产生一个外部进程和 立即返回其进程指示符,而无需等待它 终止。 "

    如果您对返回状态不感兴趣,您可以使用 exec 代替,也可以使用 fork/thread 进行并行执行。

    【讨论】:

    • 如果您担心 CPU 周期,您还需要避免浪费一秒钟 perl
    猜你喜欢
    • 2010-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-29
    • 2017-10-26
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多