【问题标题】:Error with accessing Array name in perl在 perl 中访问数组名称时出错
【发布时间】:2014-01-29 02:52:12
【问题描述】:

我在 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.

【问题讨论】:

  • 不要那样做。使用二维数组。

标签: perl


【解决方案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 
}

【讨论】:

  • 我很困惑.. 你能举个小例子吗.. 还有可以用名字来引用每一行吗?因为我应该从哪一行两个元素匹配
  • 好吧,您可以使用一个变量来存储您当前匹配的数组。我将在上面进行编辑以举一个例子。
猜你喜欢
  • 2017-01-11
  • 1970-01-01
  • 2012-06-03
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 2015-04-28
相关资源
最近更新 更多