References to Perl Array and the exception of "Argument type 1 for keys must be hashes"

I have a $subscribers scalar, which can be undef, a reference to HASH, or a link to ARRAY. I assigned sample values $VAR1 , $VAR2 and $VAR3 for testing.

I'm only interested in $subscribers when this is a link to ARRAY, where it will contain multiple values. In other cases, I do not need to print anything (for example, when $subscribers=$VAR2;

The code seems to work under Perl v5.16.2; however, when I move it to the target machine with Perl v5.8.8, I get a compilation 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"; 
+7
arrays perl perl-data-structures hash ref
source share
1 answer

Replace

 foreach my $s (keys $subscribers) { 

from

 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 accept scalar EXPR, which must contain a reference to a useless hash or array. The argument will be dereferenced automatically. This aspect of keys is considered highly experimental. Exact behavior may change in a future version of Perl.

+13
source share

All Articles