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

I have run through several different scenarios with this particular piece of code and each time I get the same error "Cannot coerce hash into array" Can someone give me an outside perspective, I am just trying to compare a certain value from each key to a set variable:
foreach $currentkey (keys %temp_dcr) { if ("$temp_dcr{$currentkey}{RightNavLaunchDate}" le $today) {
Thanks, Bill

Replies are listed 'Best First'.
(tye)Re: How is this syntax breaking my code?
by tye (Sage) on May 17, 2001 at 03:33 UTC

    First, you don't need those quotes.

    Second, if you use diagnostics or -Mdiagnostics (on the Perl command line), then you'll get an explanation of the error message.

    Third, I couldn't see how that error would apply to the code you give so I tried to look up the error in perldiag.pod (which contains all of the error descriptions that use diagnostics can give you). There is no such error. There is this:

    Can't coerce array into hash

    (F) You used an array where a hash was expected, but the array has no information on how to map from keys to array indices. You can do that only with arrays that have a hash reference at index 0.

    So it looks like you got the error message backward and that $temp_dcr{$currentkey} contains a reference to an array (instead of a reference to a hash) for at least one value of $currentkey. (The explanation of the error might be a bit confusing if you don't know about pseudo-hashes, which are being phased out so don't worry about them.)

    You can look at how you are populating $temp_dcr to try to figure out how an array reference is getting in there. Or you could debug the problem (use the perl debugger's "x" command or Data::Dumper to display what the contents of $temp_dcr look like before you enter the loop, for example).

            - tye (but my friends call me "Tye")
Re: How is this syntax breaking my code?
by Anonymous Monk on May 16, 2001 at 23:26 UTC
    One {} Pair interpolates in "" without -> not 2.

      Not true. You can go down complex data structures as deeply as you want. And arrows are optional between two sets of brackets.

      --
      <http://www.dave.org.uk>

      "Perl makes the fun jobs fun
      and the boring jobs bearable" - me

        That might be true in 5.6. The Arrows are optional in Program text, but in ""?