加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 21:42:39 所属栏目:大数据 来源:网络整理
导读:我有一个标量$订阅者可能是undef,引用HASH或引用ARRAY.我已经为测试分配了样本值$VAR1,$VAR2和$VAR3. 当它是对ARRAY的引用时,我只对$subscriber感兴趣,其中它包含多个值.在其他情况下,我对打印任何东西都不感兴趣(例如,当$subscriber = $VAR2; 在Perl v5.16.
我有一个标量$订阅者可能是undef,引用HASH或引用ARRAY.我已经为测试分配了样本值$VAR1,$VAR2和$VAR3.

当它是对ARRAY的引用时,我只对$subscriber感兴趣,其中它包含多个值.在其他情况下,我对打印任何东西都不感兴趣(例如,当$subscriber = $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";

解决方法

更换
foreach my $s (keys $subscribers) {

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

要么

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

从perldoc起

Starting with Perl 5.14,keys can take a scalar EXPR,which must contain a reference to an unblessed hash or array. 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读