2012-02-19 88 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