Why, when I try to access the hash element, can I get the error "I can not use the string as a HASH ref"?

How to fix this error?

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

Error: It is not possible to use string ("1249998666") as a HASH ref, while "strong links" are used on /.../BMW.pm line 222.

+7
perl
source share
3 answers

The Data::Dumper module is extremely useful in such situations to help you understand why a complex data structure does not meet your expectations. For example:

 use Data::Dumper; print Dumper(\%args); 
+11
source share

Clearly, one of the values ​​in %{ $args{car_models} } not a hash reference. That is, the data structure does not contain what you think. Thus, you can either correct the data structure or change your code in accordance with the data structure. Since you did not provide a data structure, I cannot comment on this.

You can use ref to find out if $_ a hash reference 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 powers of ESP, I assume these values ​​are timestamps. So, I assume you are trying to find the year from the timestamp value (the number of seconds from an era). In this case, you probably want localtime or gmtime :

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

In addition, specific information about what your data structure should contain is my best guess.

+9
source share

Hi, if you have a hash ref variable (e.g. $ hash_ref) then the 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")); } 

Thanks Manoah Shehawat

0
source share

All Articles