简体   繁体   English

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

[英]Perl Array References and avoiding “Type of arg 1 to keys must be hash” error

I have a scalar $subscribers that could be undef, reference to a HASH, or reference to an ARRAY. 我有一个标量$subscribers可能是undef,引用HASH或引用ARRAY。 I have assigned the sample values $VAR1 , $VAR2 and $VAR3 for testing. 我已经为测试分配了样本值$VAR1$VAR2$VAR3

I'm only interested in $subscribers when it is a reference to an ARRAY, where by it would contain multiple values. 当它是对ARRAY的引用时,我只对$subscribers感兴趣,其中它包含多个值。 In other cases, I'm not interested in printing anything (eg when $subscribers=$VAR2; 在其他情况下,我对打印任何东西都不感兴趣(例如,当$subscribers=$VAR2;

The code seems to run fine under Perl v5.16.2; 在Perl v5.16.2下,代码似乎运行良好; however, when I move it to the target machine running Perl v5.8.8, I get a compile error : 但是,当我将它移动到运行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.

Code below: 代码如下:

#!/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";

Replace 更换

foreach my $s (keys $subscribers) {

with

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

or 要么

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

From perldoc 来自perldoc

Starting with Perl 5.14, keys can take a scalar EXPR, which must contain a reference to an unblessed hash or array. 从Perl 5.14开始,密钥可以采用标量EXPR,它必须包含对未经处理的散列或数组的引用。 The argument will be dereferenced automatically. 该参数将自动解除引用。 This aspect of keys is considered highly experimental. 钥匙的这个方面被认为是高度实验性的。 The exact behaviour may change in a future version of Perl. 在未来的Perl版本中,确切的行为可能会发生变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM