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

前端 未结 3 976
灰色年华
灰色年华 2021-01-04 23:28

How do I fix this error?

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

Error:

相关标签:
3条回答
  • 2021-01-04 23:59

    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")); 
    }
    
    0 讨论(0)
  • 2021-01-05 00:10

    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);
    
    0 讨论(0)
  • 2021-01-05 00:22

    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.

    0 讨论(0)
提交回复
热议问题