【问题标题】:How can I pass arguments to an external process from Perl?如何从 Perl 将参数传递给外部进程?
【发布时间】:2011-01-19 08:49:47
【问题描述】:

我有一个应用程序可执行文件,它使用不同的参数运行以产生不同的输出。我想从脚本的命令行参数中为此提供一些参数,而其他参数将是脚本的本地参数。用法:

./dump-output.pl <version> <folder-name> <output-file>


my $version = $ARGV[0];
my $foldername = $ARGV[1];
my $outputfile = $ARGV[2];
my $mkdir_cmd = "mkdir -p ~/$foldername";

# There are 6 types of outputs, which can be created:
# 'a', 'b', 'c', 'd', 'e' or 'f'
my @outputtype = ('a', 'b', 'c', 'd', 'e', 'f');

my $mkdir_out = `$mkdir_cmd`;

for( $itr=0; itr<=5; itr++ ) {
    $my_cmd = "./my_app -v $version -t $outputtype[itr] -f $outputfile > ~/$foldername/$outputtype.out"
    $my_out = `$my_cmd`;
}

我在上面的代码中做了一些固有的错误,但无法弄清楚:-(

【问题讨论】:

  • 有一个模块可以为您处理该 mkdir。 :)
  • 当您不知道为什么某个命令不起作用时,打印您尝试运行的内容以确保它是您认为的内容。

标签: perl command-line arguments external-process


【解决方案1】:
# Always include these at the top of your programs.
# It will help you find bugs like the ones you had.
use strict;
use warnings;

# You can get all arguments in one shot.
my ($version, $foldername, $outputfile) = @ARGV;

# A flag so we can test our script. When
# everything looks good, set it to 1.
my $RUN = 0;

my $mkdir_cmd = "mkdir -p ~/$foldername";
my $mkdir_out = run_it($mkdir_cmd);

# Word quoting with qw().
my @outputtype = qw(a b c d e f);

# If you already have a list, just iterate over it --
# no need to manually manage the array subscripts yourself.
for my $type (@outputtype) {
    my $my_cmd = "./my_app -v $version -t $type -f $outputfile > ~/$foldername/$type.out";
    my $my_out = run_it($my_cmd);
}

# Our function that will either run or simply print
# calls to system commands.
sub run_it {
    my $cmd = shift;
    if ($RUN){
        my $output = `$cmd`;
        return $output;
    }
    else {
        print $cmd, "\n";
    }
}

【讨论】:

  • +1 表示use strict;use warnings; - 这将立即给出大部分失败的原因。我不太确定其余的重写 - 没有必要。
  • 此解决方案违反了多项安全实践。您永远不应该获取外部数据并将其直接传递给另一个进程。
  • #!/usr/bin/perl -T 用于污点模式。见:perldoc perlsec
  • @brian 从不覆盖广阔的领域。
【解决方案2】:

for 循环缺少$

输出类型数组缺少索引的$itr

可能还有更多——我还没有测试过。这是显而易见的东西。

看起来您可能来自像 C 这样的语言,其中变量可以是诸如“i”之类的裸词。 perl 中的变量总是以$ 开头标量,@ 列表,% 哈希。

【讨论】:

    猜你喜欢
    • 2014-08-20
    • 2012-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多