0

So I have a massive hash of hashes.

$VAR1 = {
          'Peti Bar' => {
                          'Mathematics' => 82,
                          'Art' => 99,
                          'Literature' => 88
                        },
          'Foo Bar' => {
                         'Mathematics' => 97,
                         'Literature' => 67
                       }
        };

There's an example I found on the web.

What I want to print is 'Peti Bar' and 'Foo Bar', but it's not quite that simple. Imagine Mathematics being it's own hash within that hash, etc. So I'd wanta to print 'Peti Bar' -> 'Mathematics' -> 'AnotherHash' 'Foo Bar' -> 'Literature' -> 'Anotherhash'

I guess maybe what I'm asking is print the hash of hashes without key/value of each respective hash.

Ben
  • 749
  • 1
  • 7
  • 18

2 Answers2

1

The easiest way is probably to use a recursive function to go through the top-level hash and any subhashes, printing any keys that have subhashes before descending into the subhash:

#!/usr/bin/env perl    

use strict;
use warnings;
use 5.010;

my %bighash = (
  'Peti Bar' => {
    'Mathematics' => {    
      'Arithmetic' => 7,    
      'Geometry'   => 8,    
      'Calculus'   => 9,    
    },
    'Art'        => 99,   
    'Literature' => 88    
  },                    
  'Foo Bar' => {
    'Mathematics' => 97, 
    'Literature'  => 67  
  }                    
);      

dump_hash(\%bighash);

sub dump_hash {
  my $hashref = shift;
  my @parents = @_;

  return unless $hashref && ref $hashref eq 'HASH';

  for my $key (sort keys %$hashref) {
    my $val = $hashref->{$key};
    next unless ref $val eq 'HASH';
    say join ' -> ', @parents, $key;
    dump_hash($val, @parents, $key);
  }
}

Output:

Foo Bar
Peti Bar
Peti Bar -> Mathematics
Dave Sherohman
  • 45,363
  • 14
  • 64
  • 102
0

Similar to Dave S

use strict;

my $VAR1 = {
          'Peti Bar' => {
                          'Mathematics' => 82,
                          'Art' => 99,
                          'Literature' => 88
                        },
          'Foo Bar' => {
                         'Mathematics' => 97,
                         'Literature' => 67
                       }
        };


sub printHash($$) {
    my $hashRef = shift;
    my $indent = shift;
    for (keys %$hashRef) {
        if (ref($hashRef->{$_}) eq 'HASH') {
            print "$indent$_ \n";
            printHash($hashRef->{$_},"\t$indent");
        }
        else {
            print "$indent$_  $hashRef->{$_}\n";
        }
    }
}

printHash($VAR1,undef);

Output is :

Foo Bar
        Mathematics  97
        Literature  67
Peti Bar
        Literature  88
        Mathematics  82
        Art  99
Essex Boy
  • 7,565
  • 2
  • 21
  • 24