Perl错误:参数在数组或散列查找中不是数字

时间:2016-04-13 03:47:19

标签: perl

我正在编写一个简单的程序来将单词与正则表达式模式匹配。但我一直收到上面的错误。这是我的代码:

my @words = ("Ordinary", "order", "afford", "cordford", "'ORD airport'");
foreach my $index (@words) {
    if ($words[$index] =~ m/ord/) {
        print "match\n";
    } else {print "no match\n";}
}

我收到错误:

Argument "Ordinary" isn't numeric in array or hash lookup at test.pl line  6.
Argument "order" isn't numeric in array or hash lookup at test.pl line 6.
Argument "afford" isn't numeric in array or hash lookup at test.pl line 6.
Argument "cordford" isn't numeric in array or hash lookup at test.pl line 6.
Argument "'ORD airport'" isn't numeric in array or hash lookup at test.pl line 6.
no matchno matchno matchno matchno match

任何人都可以向我解释导致错误的原因是什么?

3 个答案:

答案 0 :(得分:4)

这是你展示的代码(改进了一点)

my @words = ( 'Ordinary', 'order', 'afford', 'cordford', q{'ORD airport'} );

    for my $index ( @words ) {

        if ( $words[$index] =~ /ord/ ) {
            print "match\n";
        }
        else {
            print "no match\n";
        }
    }
}

for循环会将$index设置为@words数组中的每个。因此,例如,第一次执行循环$index将设置为Ordinary;第二次将它设置为order等。

命名$index清楚地表明您希望它包含@words的所有索引。您可以这样做,就像这样

for my $index ( 0 .. $#words ) { ... }

如果您做出改变,您的程序将正常工作。输出是

no match
match
match
match
no match

但是从一开始你就有了正确的想法。大多数情况下,数组只是一个值列表,而索引没有相关性。这适用于您的情况,您可以写

for my $word ( @words ) {

    if ( $word =~ m/ord/ ) {
        print "match\n";
    }
    else {
        print "no match\n";
    }
}

或使用Perl的默认变量 $_可以编写

for ( @words ) {

    if ( m/ord/ ) {
        print "match\n";
    }
    else {
        print "no match\n";
    }
}

甚至只是

print /ord/ ? "match\n" : "no match\n" for @words;

上面的每个例子都是完全等效的,所以产生相同的输出

答案 1 :(得分:1)

原因是你的$index将生成数组的元素而不是索引值。

它应该是foreach my $index (0..$#words)现在$index将在每次迭代中生成数组的索引。

use strict; 
use warnings;

my @words = ("Ordinary", "order", "afford", "cordford", "'ORD airport'");

foreach my $index (0..$#words) {

    if ($words[$index] =~ m/ord/) {

       print "match\n";
    } 

    else {print "no match\n";}
 }

否则。只需使用$index检查条件即可。

use strict; 

use warnings;

my @words = ("Ordinary", "order", "afford", "cordford", "'ORD airport'");

foreach my $index (@words) {

    if ($index =~ m/ord/) {

    print "match\n";

    }

    else {print "no match\n";}
}

答案 2 :(得分:0)

这是数组查找

$words[$index];

如果它是哈希,那将是

$words{$index};

数组期望整数索引,但您使用的字符串看起来不像整数。

如果你在Perl中迭代数组,你就不需要索引..

#!/usr/bin/perl
use strict;
use warnings;

my @words = ("Ordinary", "order", "afford", "cordford", "'ORD airport'");
foreach my $word (@words) {
  if($word =~ m/ord/) {      
    print "$word match\n";
  } else {
    print "$word no match\n";
  }
}

请注意。我已使用foreach,因为您可以使用更多语言查看for

您也可以尝试一些替代方案,注意这不会结束,但值得研究,

#!/usr/bin/perl
use strict;
use warnings;
my @words = ("Ordinary", "order", "afford", "cordford", "'ORD airport'");
my $iterator = sub {
  my $item = shift(@words);
  push(@words, $item);
  return $item;
};

while(my $item = $iterator->()) {
  print("$item\n");
}

我爱Perl。

相关问题