Perl的数组引用,避免与QUOT; ARG 1类型为密钥必须散列"错误 [英] Perl Array References and avoiding "Type of arg 1 to keys must be hash" error
问题描述
我有一个标量 $用户
这可能是联合国民主基金,参照HASH,或引用数组。我已经指定了采样值 $ VAR1
, $ VAR2
和 $ VAR3
进行测试。
我只对 $用户感兴趣
当它到一个数组中,通过在那里将包含多个值的参考。在其他情况下,我不感兴趣的任何印刷时(例如 $用户= $ VAR2;
在code似乎在Perl的v5.16.2运行良好;然而,当我将它移动到目标机器上运行的的Perl v5.8.8,我得到一个编译错误
%./test.pl
ARG 1类型钥匙必须在./test.pl线是哈希值(不是私有变量)23,近$用户)
由于编译错误中止./test.pl的执行。
code如下:
#!的/ usr / bin中/ perl的-w使用严格的;
使用警告;
使用数据::自卸车;我的$ VAR1 =民主基金;我的$ VAR2 = {'MSISDN'=> '1234'};我的$ VAR3 = [
{'MSISDN'=> '1111'},
{'MSISDN'=> 2222},
{'MSISDN'=> 3333},
{'MSISDN'=> 4444},
{'MSISDN'=> '5555'}
];我@childMsisdn =();
我的$用户= $ VAR3;如果(参考$用户EQ文献[]){#$排除VAR1&放大器;&安培; $ VAR2方案
我的foreach $ S($键用户){
我的$ MSISDN = $ subscribers-> [$ S] - > {MSISDN};
推(@childMsisdn,$ MSISDN);
}
}
打印childMsisdn =。加入(,,@childMsisdn)\\ N。
替换
我的foreach $ S($键用户){
与
我的foreach $ S(键%$用户){#$用户是哈希REF
或
我的foreach $ S(0 .. $#$用户){#$用户是数组引用
通过的perldoc
用Perl 5.14起,钥匙可以采取标量EXPR,其中必须包含一个unblessed散列或数组的引用。该参数将被自动取消引用。按键的这个方面被认为是高度实验性的。确切的行为可能在Perl的未来版本中改变。
块引用>I have a scalar
$subscribers
that could be undef, reference to a HASH, or reference to an ARRAY. I have assigned the sample values$VAR1
,$VAR2
and$VAR3
for testing.I'm only interested in
$subscribers
when it is a reference to an ARRAY, where by it would contain multiple values. In other cases, I'm not interested in printing anything (e.g. when$subscribers=$VAR2;
The code seems to run fine under Perl v5.16.2; however, when I move it to the target machine running Perl v5.8.8, I get a compile error:
% ./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
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.
这篇关于Perl的数组引用,避免与QUOT; ARG 1类型为密钥必须散列"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!