访问perl中的数组名称的错误



我正在在Perl中进行一个项目,以搜索具有所有其他元素的数组中的每个元素,并打印匹配中元素的元素和数组名称。

由于代码很长,所以我用简短的例子解释了我的问题。

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

当我尝试使用上述方法搜索模式时,我会得到答案。因为有很多数组,每个数组包含我给我的许多元素,我给了数组名称为 @array1, @array2 ...,以便我可以使用loops搜索。

所以我尝试了此方法

@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:Perl64pracpp.pl line 4, near "$arra$no"
Execution of C:Perl64pracpp.pl aborted due to compilation errors.

将所有数组保持在相同的结构中要简单得多,您可以将任意多的arrayref放在阵列内部,并在它们的嵌套循环中迭代它们:

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_countern"; }
   }
   $array_counter++; # increment counter 
}

最新更新