3

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};
   }
}
Eric Fossum
  • 2,395
  • 4
  • 26
  • 50

2 Answers2

4

$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.

mob
  • 117,087
  • 18
  • 149
  • 283
1

I'm guessing you say "options" there where you mean "HASH"?

Hashes only store scalars, not other hashes; each value of %HASH is a hash reference that needs to be dereferenced, so your inner loop should be:

foreach my $inner (keys(%{ $HASH{$key} })

Or:

my %HASH = ('first'=>{'A'=>50, 'B'=>40, 'C'=>30},
            'second'=>{'A'=>-30, 'B'=>-15, 'C'=>9});
foreach my $key (keys(%HASH))
{
    my $innerhash = $HASH{$key};
    foreach my $inner (keys(%$innerhash))
    {
        print "Match: ".$otherhash{$key}->{$inner}." ".$innerhash->{$inner};
    }
}
ysth
  • 96,171
  • 6
  • 121
  • 214