如何从Perl向外部进程传递参数?

时间:2010-02-21 15:41:59

标签: perl command-line arguments external-process

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

./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`;
}

我正在做上述代码的本质错误,但无法弄明白: - (

2 个答案:

答案 0 :(得分:4)

# 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 :(得分:3)

for循环缺少$

outputtype数组缺少索引

$itr

可能还有更多 - 我还没有测试过。这是显而易见的事情。

看起来你好像是来自像C这样的语言,变量可以是像“i”这样的简单字。 perl中的变量始终以标量为$,列表为@,哈希为%