无法访问嵌套哈希值中的值

时间:2011-10-27 21:56:50

标签: perl

我正在尝试访问一些深入哈希的列表。这是我的代码:

my %english = (
    greetings => [("Hello", "What's up?")],
);

my %spanish = (
    greetings => [("Hola", "Que pasa?")],
);

my %bighash = (
    english => %english,
    spanish => %spanish,
);

print 'English greetings: ';
if (my $array = $bighash{'english'}{'greetings'}) {
    print "\n$_" for @$array
}
else {
    print 'Fail.';
}

但是,if条件始终计算为“false”。这是为什么?

1 个答案:

答案 0 :(得分:5)

表达式

english => %english,
spanish => %spanish,

不正确,因为哈希值必须是标量(例如哈希引用)而不是哈希。试试

english => \%english,
spanish => \%spanish,

english => { %english },
spanish => { %spanish },

代替。