tags:

views:

374

answers:

2

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.

+3  A: 

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.

Sinan Ünür
My intent is to push these numbers into the @non_sorted_models array as numbers so that I can call sort on the array. How do I convert it into an integer
Kys
By the way, putting those checks in place still gave me the same errors.
Kys
@Kys I do not understand what you are saying. Are you saying `values %{ $args{car_models} }` are not supposed to be hash references? If that is the case, why are you dereferencing them as if they are supposed to be? **Show your data structure** Otherwise this is a case of the blind leading the blind.
Sinan Ünür
Here is how it looks like:{ 'four-wheel' => 'true', 'description' => 'Lightning fast', 'producer' => { 'name' => {} }, 'year' => '2009-08-07T22:31:06Z', };
Kys
And yes they are timestams that I want to convert to num secs from an epoch. I dunno if you read the stuff I posted on the other link, but it's strange that the erros disappear if I have my logger print out the values first.
Kys
+2  A: 

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);
FM