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

What's wrong with this 2-dimensional hash? It says that $gra{$k} is not a hash, but it should be the other dimension of the hash. Any ideas what I'm doing wrong?
my %gra; $gra{"test"}{"A"}=44; $gra{"test"}{"B"}=41; $gra{"foo"}{"A"}=43; for my $k (keys %gra) { print $k,"\n"; for my $i (keys $gra{$k}) { my $v=$gra{$k}{i}; print "$i: $v\n"; } }

Replies are listed 'Best First'.
Re: Two-dimensional hash problem
by diotalevi (Canon) on Nov 04, 2005 at 21:39 UTC

    $gra{$k} is a reference, not a hash. Enclose it in %{...} like %{$gra{$k}}.

Re: Two-dimensional hash problem
by Tanktalus (Canon) on Nov 04, 2005 at 21:40 UTC

    First thing I notice is the lack of $ in the {i} on the fourth-last line (first line inside the inner for loop).

    Second thing I notice is your indentation. It's a bit much.

    Third thing I notice is that keys requires a hash, not a hash ref. The inner for loop should be:

    for my $i (keys %{$gra{$k}})
    You need to dereference that reference.

      Thanks a lot! The "i" instead of "$i" was a mistake when I simplified the problem from my code for the this forum, I know it's wrong.