Perl数组引用并避免“arg 1到键的类型必须是哈希”错误

时间:2013-12-29 11:57:00

标签: arrays perl hash ref perl-data-structures

我有一个标量$subscribers可能是undef,引用HASH或引用ARRAY。我已将样本值$VAR1$VAR2$VAR3分配用于测试。

我只对$subscribers感兴趣,当它是对ARRAY的引用时,它会包含多个值。在其他情况下,我对打印任何内容都不感兴趣(例如,当$subscribers=$VAR2;

在Perl v5.16.2下,代码似乎运行良好;但是,当我将它移动到运行 Perl v5.8.8的目标机器时,我收到编译错误

% ./test.pl
Type of arg 1 to keys must be hash (not private variable) at ./test.pl line 23, near "$subscribers) "
Execution of ./test.pl aborted due to compilation errors.

以下代码:

#!/usr/bin/perl -w

use strict;
use warnings;
use Data::Dumper;

my $VAR1 = undef;

my $VAR2 = {'msisdn' => '1234'};

my $VAR3 = [
  {'msisdn' => '1111'},
  {'msisdn' => '2222'},
  {'msisdn' => '3333'},
  {'msisdn' => '4444'},
  {'msisdn' => '5555'}
];

my @childMsisdn = ();
my $subscribers = $VAR3;

if (ref $subscribers eq ref []) { # Exclude $VAR1 && $VAR2 scenarios
  foreach my $s (keys $subscribers) {
    my $msisdn = $subscribers->[$s]->{"msisdn"};
    push (@childMsisdn, $msisdn);
  }
}
print "childMsisdn = ". join(",", @childMsisdn) ."\n";

1 个答案:

答案 0 :(得分:16)

替换

foreach my $s (keys $subscribers) {

foreach my $s (keys %$subscribers) { # $subscribers is hash ref

foreach my $s (0 .. $#$subscribers) { # $subscribers is array ref

来自perldoc

  

从Perl 5.14开始,键可以采用标量EXPR,它必须包含对未经处理的散列或数组的引用。该参数将自动解除引用。钥匙的这个方面被认为是高度实验性的。在未来的Perl版本中,确切的行为可能会发生变化。