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

This is mostly academic, since I can make this work in another way, but I know I've done this before in a different way and I can't remember what I used - and it's driving me nuts!

I haven't been using Perl for a while, other than a few scripts here and there when I needed to throw something small together, so I'm out of touch. I'm using a hash of hashes. I know how to get to the elements in the nested hash, but I'm trying to get the keys for that nested hash instead.

I have this:

$form{$field} = \%field; ... foreach $key1 (keys %form) { print "Key: $key1\n"; $t1 = ${form{$key1}}; foreach $key2 (keys %$t1) { print "\tName: $key2, Value: $$t1{$key2}\n"; #Same results - testing different format print "\tName: $key2, Value: $form{$key1}{$key2}\n"; } }

I've done this before without a temporary variable like $t1. It's just nagging me - I can't remember the format I can use so I can get the keys from the nested hash without having to use a temporary variable.

I've found a number of pages with material on hashes of hashes, but they tend to assume you know all the keys and won't be trying to get them to iterate through them.

So how could I get the keys from the nested hash without an interim variable?

Replies are listed 'Best First'.
Re: Getting Keys From Hash In a Hash
by 2teez (Vicar) on Aug 08, 2013 at 18:38 UTC

    Like this:

    my %form; my %field = ( 'key 1' => 'value 1', 'key 2' => 'value 2', ); $form{another_hash} = \%field; for my $first_key ( keys %form ) { for my $hoh_keys ( keys %{ $form{$first_key} } ) { print $hoh_keys, $/; ## get the keys } }
    You can also check perldsc. or **Specifically: Access and Printing of a HASH OF HASHES
    You really can use Data::Dumper to see how the data structure looks like, then you can get at what you want.
    use Data::Dumper; ... print Dumper \%form;
    produces..
    $VAR1 = { 'another_hash' => { 'key 2' => 'value 2', 'key 1' => 'value 1' } };
    ** Updates.

    If you tell me, I'll forget.
    If you show me, I'll remember.
    if you involve me, I'll understand.
    --- Author unknown to me

      Thank you!

      My mistake was that when I used this:

      keys %{ $form{$first_key} }
      I was leaving out the $ in front of form, like this:
      keys %{ form{$first_key} }

      So I at least remembered some of what I was doing - forgot how to treat it within the brackets.