2010-02-21 72 views
0

我有一個應用程序可執行文件,它運行不同的參數來產生不同的輸出。我想給腳本的命令行參數提供一些參數,而其他參數則是腳本的本地參數。用法:如何將參數傳遞給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

回答

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

3

for循環已經失蹤$

的輸出類型數組缺少$itr該指數

可能還有更多。 - 我沒有測試過這是顯而易見的東西

它看起來也許你是來自像C這樣的語言,其中一個變量可以是「i」這樣的空白字。 perl中的變量總是以$爲標量,@爲列表,%爲散列。

相關問題