Search code examples
perlhashmaphashtable

Getting nth/last value inside a hash of hashes


I'm trying to make a hash of hashes to uniquely identify the number that only comes under one set of levels. The hash structure looks something like this:

my %gh = {
      'Test1' => {
                   'level1a' => {
                           'level2b' => {
                                   'level3a' => {
                                           'level4a' => {
                                                   'level5' => '63'
                                                 }
                                         }
                                 }
                         }
               }
      };           

What is the simplest way to traverse the hash so I can get the value 63?

I have been using:

my $x = '';
foreach my $l0 (%gh){
          foreach my $l1 (%{$l0}){
           foreach my $l2 (%$l1){
            foreach my $l3 (%{$l2}){
             foreach my $l4 (%$l3){
              foreach my $l5 (%{$l4}){
               $x = $l5;
              }
             }
            }
           }
          }
         }    

This process seems to be working fine, but I was just looking for something simpler and shorter.


Solution

  • If you use a reference to a hash instead, here is one way:

    use warnings;
    use strict;
    
    my $gh = {
          'Test1' => {
                       'level1a' => {
                               'level2b' => {
                                       'level3a' => {
                                               'level4a' => {
                                                       'level5' => '63'
                                                     }
                                             }
                                     }
                             }
                   }
          };           
    
    print $gh->{Test1}{level1a}{level2b}{level3a}{level4a}{level5}, "\n";
    

    See also: perldoc perldsc and Data::Diver