2012-02-19 25 views
2

我創建具有3元一個txt文件陣列中的每個元素和我寫了這個代碼:做獨特的工作

my $in_file1 = 'file.txt'; 
open DAG,$in_file1; 
my @shell=<DAG>; 
close DAG; 
chomp(@shell); 
foreach my $shell(@shell){ 
# and etc code 

,我想,如果要素的數量爲0做一些事情,如果1做其他事情,如果2 ...。例如

if (@shell[0]) print "hi"; if(@shell[1]) print "bye" if(@... 

我該怎麼辦?這樣做的最好和最簡單的方法是什麼?謝謝 。

回答

2

基於值做工作的最好方法之一是哈希/重定向表,特別是如果您需要在程序中多次執行此類工作時。這涉及到創建一個散列,其中的鍵是選擇器值,值是對執行工作的子例程的引用。

在你的情況,你是根據詞的#幹什麼的,所以查找陣列是一個很好的路要走:

sub bye { print "bye"; } 
my @actions = (
    sub { },   # do nothing for 0. Using anonymous sub 
    sub { print "hi" }, # print "hi" for 1 
    \&bye,    # for 2 - illustrate how to use reference to existing sub 
); 
use File::Slurp; # To read the file 
my @lines = read_file("my_file"); 
for (my $index = 0; $index < @lines; $index++) { 
    &{ $actions[$index] }($lines[$index]); 
    # Call the sub stored in an array in correct place 
    # Pass it the line value as argument if needed. 
} 
+0

我認爲它最困難的編程部分,由於DVK – user1212132 2012-02-19 22:21:07

+1

@ user1212132 - 不清楚你最難的部分是什麼意思。此外,在StackOverflow上,它被認爲是一種很好的形式(通過點擊答案旁邊的複選標記)接受答案,如果它有幫助,作爲感謝形式:) – DVK 2012-02-19 22:22:46

+0

是否知道這個錯誤的原因:不是足夠的參數索引在第10行附近「索引」「 – user1212132 2012-02-19 22:31:23