in reply to Re: Re: HoH Weirdness
in thread HoH Weirdness

As everybody else says,

$hash{ 'key1' }{ 'key2' }

takes the contents of $hash{ 'key1' } to be a symbolic reference, and then tries to get the value of that corresponds to 'key2' against a hash with the name = $hash{ 'key1' }

So

$hash{ 'key1' } = 'foo'; $hash{ 'key1' }{ 'key2' } = 'bar'; # (2) # (2) means find %(current pkg)::foo and do $(current pkg)::foo{ 'key2' } = 'bar';

Still a hash of hashes, but I find this rather tricky to use. You always have to be aware of the fact that $hash{ 'key1' }{ 'key2' } is being evaluated via symbols

However, $hash{ 'key1' }->{ 'key2' } would be used like this:

my %hash; $hash{ 'key1' } = {}; ## ref to hash $hash{ 'key1' }->{ 'key2' } = 'foo'; ## above equivalent to my %hash = ( key1 => { key2 => 'foo' } );

And, of course, I wrote up to here and realized that it doesn't really fit to the original problem! sigh.

I probably should have pointed to

$hash{ 'key1' } = 'foo'; $hash{ 'key1', 'key2' } = 'bar';

But I really dislike that notation. ( and the way things gets stored when you do it that way )

As for the original problem, I would have done:

my %hash = ( food => { name => 'Apple', color => 'Red' } ); my $food = $hash{ 'food' }; print "$food->{ 'color' } $food->{ 'name' }\n";

Is this explanation better ? :-)

Replies are listed 'Best First'.
Re: Re: Re: Re: HoH Weirdness
by chipmunk (Parson) on Jun 09, 2001 at 02:18 UTC
    I think a review of perlref is in order. $hash{ 'key1' }{ 'key2' } and $hash{ 'key1' }->{ 'key2' } are exactly equivalent.

    ->, the dereferencing operator, is optional between subscripts.

Re4: HoH Weirdness
by John M. Dlugosz (Monsignor) on Jun 09, 2001 at 02:22 UTC
    No, I still wonder. Perlref says "The arrow is optional between brackets subscripts" so I don't see how explicitly putting the arrow in makes the compiler do things differently -- it still needs the first subscript to return a reference, and it doesn't matter whether it's symbolic or not.