Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!

I have a program that has this line causing this error to the browser:

Can't coerce array into hash at ...

This is the line causing it:

my $year = $AoH{ data }->{ 'YEAR' } || '';


Any explanation on how and why this is happening, how can I prevent this?
Thanks for the help!

Replies are listed 'Best First'.
Re: Coerce array into hash problem
by thezip (Vicar) on Oct 03, 2008 at 16:05 UTC

    This is happening because you're not dereferencing an array.

    Maybe something like:

    use strict; use warnings; use Data::Dumper; # This will give you a clearer idea of what you data actually looks li +ke print Dumper($AoH); # This assumes that $data is an index (integer) my $year = $AoH->[$data]{'YEAR'};

    If this doesn't work for you, post the contents of the Data::Dumper output, and we'll talk some more.



    What can be asserted without proof can be dismissed without proof. - Christopher Hitchens
Re: Coerce array into hash problem
by Fletch (Bishop) on Oct 03, 2008 at 16:04 UTC

    The value in the incredibly poorly named $AoH{ data } (if anything by the actual type and contents it's an HoA, but I digress) is an array reference not a hash reference, yet you're trying to treat it as a hash ref. You need to take three steps back and rethink your data structure and how you're going to lay things out (Data::Dumper and/or YAML::Syck can be illuminating figuring out what you've really got).

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: Coerce array into hash problem
by psini (Deacon) on Oct 03, 2008 at 16:03 UTC

    If $AoH is an array of hashes, then your line should be my $year = $AoH[ data ]->{ 'YEAR' } || '';

    As it is now, it tries to coerce the array $AoH into a hash, and fails.

    Rule One: "Do not act incautiously when confronting a little bald wrinkly smiling man."

      Um, wouldn't there be a problem using a bare word ("data") as an array index?

      With use strict;, such a thing would not be allowed; without the stricture, the bare word evaluates to zero when interpreted in a numeric context, and this is probably not the real intention...