Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to construct a hash of hashes

I need to compare two hashes, but I can't get the inner set of keys...

my %HASH = ('first'=>{'A'=>50, 'B'=>40, 'C'=>30},
            'second'=>{'A'=>-30, 'B'=>-15, 'C'=>9});
foreach my $key (keys(%HASH))
{
   my %innerhash = $options{$key};
   foreach my $inner (keys(%innerhash))
   {
      print "Match: ".$otherhash{$key}->{$inner}." ".$HASH{$key}->{$inner};
   }
}
like image 987
Eric Fossum Avatar asked Dec 05 '25 18:12

Eric Fossum


1 Answers

$options{$key} is a scalar (you can tell be the leading $ sigil). You want to "dereference" it to use it as a hash:

my %HASH = ('first'=>{'A'=>50, 'B'=>40, 'C'=>30},
            'second'=>{'A'=>-30, 'B'=>-15, 'C'=>9});
foreach my $key (keys(%HASH))
{
   my %innerhash = %{ $options{$key} };  # <---- note %{} cast
   foreach my $inner (keys(%innerhash))
   {
      print "Match: ".$otherhash{$key}->{$inner}." ".$HASH{$key}->{$inner};
   }
}

When you're ready to really dive into these things, see perllol, perldsc and perlref.

like image 74
mob Avatar answered Dec 08 '25 10:12

mob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!