Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get "Can't use string as a HASH ref" error when I try to access a hash element?

Tags:

perl

How do I fix this error?

foreach (values %{$args{car_models}}) {
   push(@not_sorted_models, UnixDate($_->{'year'},"%o"));
}

Error: Can't use string ("1249998666") as a HASH ref while "strict refs" in use at /.../BMW.pm line 222.

like image 445
Kys Avatar asked Aug 12 '09 17:08

Kys


3 Answers

Hi if you have a hash ref variable (like $hash_ref) then code will be

if ( ref($hash_ref) eq 'HASH' and exists $hash_ref->{year} ) {
    push(@not_sorted_models, UnixDate($hash_ref->{year},"%o")); 
}
#instead of below:
if ( ref eq 'HASH' and exists $_->{year} ) {
    push(@not_sorted_models, UnixDate($_->{year},"%o")); 
}
like image 78
Manoj Shekhawat Avatar answered Sep 24 '22 05:09

Manoj Shekhawat


Clearly, one of the values in %{ $args{car_models} } is not a hash reference. That is, the data structure does not contain what you think it does. So, you can either fix the data structure or change your code to match the data structure. Since you have not provided the data structure, I can't comment on that.

You could use ref to see if $_ contains a reference to a hash before trying to access a member.

if ( ref eq 'HASH' and exists $_->{year} ) {
    push(@not_sorted_models, UnixDate($_->{year},"%o")); 
}

Based on your comment, and my ESP powers, I am assuming those values are timestamps. So, I am guessing, you are trying to find the year from a timestamp value (number of seconds from an epoch). In that case, you probably want localtime or gmtime:

my $year = 1900 + (localtime)[5];
C:\Temp> perl -e "print 1900 + (localtime(1249998666))[5]"
2009

Without further, concrete information about what your data structure is supposed to contain, this is my best guess.

like image 32
Sinan Ünür Avatar answered Sep 24 '22 05:09

Sinan Ünür


The Data::Dumper module is extremely useful in such situations -- to help you figure out why a complex data structure is not meeting your expectations. For example:

use Data::Dumper;
print Dumper(\%args);
like image 42
FMc Avatar answered Sep 23 '22 05:09

FMc