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

I have had a job change, and had to step away from the perl arena for a while. I have start a little script and I am a bit rusty. That being said, I have something that confuses me.

I have a HoH: %hash
%hash has 5 keys that are also hashes (%key1, %key2, %key3, %key4, %key5)
each of these hashes have 5 keys/value pairs.

When I undef(%hash) and I do a key count on it
$count = keys %hash;
$count = 0 and I would expect this. But when I do a key count on the hashes one level in:
$count = keys %{$hash->{$key1}};
I get $count = 5. This I did not expect!

I know that I can loop through the hash and undef everything, but why is this happening? What am I missing?

I did a super search and did not see this discussed.

Thanks in advance!
  • Comment on undef(%hash) not doing what I expect for HoH

Replies are listed 'Best First'.
Re: undef(%hash) not doing what I expect for HoH
by monarch (Priest) on Oct 12, 2006 at 14:56 UTC
    I'm confused. %hash is your hash of hashes. This implies that %hash is a hash, not a reference to a hash.

    So when you attempt to recover keys %{$hash->{$key1}} you're attempting to treat %hash as a reference. Don't you mean to try keys %{$hash{$key1}}?

    Update: actually I tried a little script of my own and when I added keys %{$hash->{$key1}} I got a compiler error saying that I hadn't defined $hash. Try adding use strict to your script and see if the compiler helps you solve the problem..

      Wow, I am rusty. You are exactly right! And of course an undef on a reference does not affect the hash and an undef on a hash that I was not even using affects it even less... Thank you!
Re: undef(%hash) not doing what I expect for HoH
by Fletch (Bishop) on Oct 12, 2006 at 15:12 UTC

    %hash is a hash; $hash is a scalar with an unfortunate name.

    $hash{foo} is the item in %hash at key "foo". $hash->{foo} is the item in the hashref stored in $hash at key "foo".

    undef %hash clears everything from %hash; $hash is untouched. undef %{ $hash } clears everything from the hash referenced by $hash; %hash is untouched. undef $hash replaces the reference to the hash which was in $hash with undef; again, %hash is untouched.

    A judicious use strict would have caught this.

Re: undef(%hash) not doing what I expect for HoH
by blazar (Canon) on Oct 12, 2006 at 15:26 UTC

    That doesn't seem to be the case for me:

    #!/usr/bin/perl -l use strict; use warnings; my %hoh=( h => {foo=>1}, g => {bar=>2} ); print scalar keys %hoh; print scalar keys %{ $hoh{h} }; undef %hoh; print scalar keys %hoh; print scalar keys %{ $hoh{h} }; __END__

    I get:

    2 1 0 0

    But I wouldn't use undef on aggregates anyway.