Perl如何访问作为另一个哈希值的数组元素的哈希?

时间:2010-11-12 01:01:08

标签: arrays perl hash perl-data-structures

我正在尝试创建一个Hash,其值为数组。

值的第一个元素(数组)是标量。 值的第二个元素(它是一个数组)是另一个哈希值。

我已将值放在此哈希的键和值中,如下所示:

${${$senseInformationHash{$sense}[1]}{$word}}++;

下面,

我的主要哈希 - > senseInformationHash

我的价值 - >是一个数组

所以,${$senseInformationHash{$sense}[1]}让我参考了我的哈希

我输入了密钥和值,如下所示:

${${$senseInformationHash{$sense}[1]}{$word}}++;

我不确定这是否是正确的方法。因为我被困住了,不知道如何打印这个复杂的东西。我想打印出来以检查我是否正确地进行了操作。

非常感谢任何帮助。提前谢谢!

3 个答案:

答案 0 :(得分:4)

只需写下

$sense_information_hash{$sense}[1]{$word}++;

并完成它。

Perl嫉妒CamelCase,你知道,所以你应该使用正确的下划线。否则它会吐痰和贬值,并且通常行为不端。

答案 1 :(得分:2)

哈希值绝不是数组,而是数组引用。

要查看您是否正确行事,您可以转储整个结构:

my %senseInformationHash;
my $sense = 'abc';
my $word = '123';
${${$senseInformationHash{$sense}[1]}{$word}}++;
use Data::Dumper;
print Dumper( \%senseInformationHash );

让你:

$VAR1 = {
      'abc' => [
                 undef,
                 {
                   '123' => \1
                 }
               ]
    };

注意\1:大概你希望值为1,而不是对标量1的引用。你得到了后者,因为你的${ ... }++;表示将花括号中的内容视为标量参考并增加所提到的标量。

${$senseInformationHash{$sense}[1]}{$word}++;可以满足您的需求,$senseInformationHash{$sense}[1]{$word}++也是如此。您可能会发现http://perlmonks.org/?node=References+quick+reference有助于了解原因。

答案 2 :(得分:0)

感谢Axeman和TChrist。

我必须访问的代码如下:

    foreach my $outerKey (keys(%sense_information_hash))
{
  print "\nKey => $outerKey\n";
  print "  Count(sense) => $sense_information_hash{$outerKey}[0]\n";

        foreach(keys (%{$sense_information_hash{$outerKey}[1]}) )
    {
        print " Word wt sense => $_\n";
        print " Count  => $sense_information_hash{$outerKey}[1]{$_}\n"; 
    }
}

现在正在运作。非常感谢!

相关问题