首页 文章

在perl中访问数组名称时出错

提问于
浏览
0

我在perl中做一个项目来搜索一个包含所有其他元素的数组中的每个元素,并打印出匹配所在的元素和数组名称 .

由于代码很长,我用简短的例子解释我的问题 .

@array1=(sdasd,asdasd,abc);

if(abc=~/$array1[2]/)
{
print"Found!";
}
else
{
print"not found!"
}

当我尝试使用上述方法搜索模式时,我得到了答案 . 由于有许多数组,每个数组包含许多元素,我给数组名称@ array1,@ array2 ...以便我可以使用循环进行搜索 .

所以我尝试了这种方法

@array1=(sdasd,asdasd,abc);

$arrayno = 1;
if(abc=~$array$arrayno[2])
{
print"Found!";
}
else
{
print"not found!"
}

我收到以下错误

(Missing operator before $no?)
syntax error at C:\Perl64\prac\pp.pl line 4, near "$arra$no"
Execution of C:\Perl64\prac\pp.pl aborted due to compilation errors.

1 回答

  • 1

    将所有数组保存在同一结构中要简单得多,您可以在数组中放置尽可能多的数组引用,并在嵌套的foreach循环中迭代它们:

    my @arrays = ( [1,  2,  3,  4],
                   [5,  6,  7,  8],
                   [9, 10, 11, 12],
                 );
    
    my $array_counter = 1; 
    foreach my $aref ( @arrays ) {
       foreach my $elem ( @$aref ) { # place arrayref in list context
          # do comparison here
          if ( # MATCH ) { print "Found match in Array $array_counter\n"; }
       }
       $array_counter++; # increment counter 
    }
    

相关问题