3

我需要比较两个哈希,但我无法获得内部键集......

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};
   }
}
4

2 回答 2

4

$options{$key}是一个标量(你可以说是领先的$印记)。您想“取消引用”它以将其用作哈希:

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};
   }
}

当您准备好深入研究这些内容时,请参阅perllol和。perldscperlref

于 2011-07-15T16:54:23.700 回答
1

我猜你在哪里说“选项”,你的意思是“哈希”?

散列只存储标量,不存储其他散列;%HASH 的每个值都是需要取消引用的哈希引用,因此您的内部循环应该是:

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

或者:

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};
    }
}
于 2011-07-15T17:05:43.583 回答