如何将参数传递给Perl的外部进程?

问题描述:

我有一个应用程序可执行文件,它运行不同的参数来产生不同的输出。我想给脚本的命令行参数提供一些参数,而其他参数则是脚本的本地参数。用法:如何将参数传递给Perl的外部进程?

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

我做什么内在的错误上面的代码,但一直没能弄明白:-(

+0

什么是错误信息? – Paul 2010-02-21 15:57:05

+0

有一个模块可以为你处理mkdir。 :) – 2010-02-21 23:32:35

+1

当你不知道为什么一个命令不起作用时,打印你正在尝试运行的内容,以确保它是你的想法。 – 2010-02-21 23:33:03

# 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"; 
    } 
} 
+0

+ 1用于'严格使用;'和'使用警告;' - 这会给大多数立即失败的原因。我不确定剩下的重写 - 这是没有必要的。 – 2010-02-21 17:01:19

+2

该解决方案违反了几种安全做法。您绝不应该将外部数据直接传递给其他进程。 – 2010-02-21 23:31:28

+1

'#!/ usr/bin/perl -T'用于污染模式。请参阅:'perldoc perlsec' – mctylr 2010-02-22 00:00:23

for循环已经失踪$

的输出类型数组缺少$itr该指数

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

它看起来也许你是来自像C这样的语言,其中一个变量可以是“i”这样的空白字。 perl中的变量总是以$为标量,@为列表,%为散列。