How do I fix this error?
foreach (values %{$args{car_models}}) {
push(@not_sorted_models, UnixDate($_->{\'year\'},\"%o\"));
}
Error:
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"));
}
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);
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.