试图在perl中迭代哈希的哈希值。这种方法有什么问题?

时间:2012-11-05 05:07:56

标签: perl hash foreach

我正在尝试迭代使用嵌套哈希的数据结构中的项目。 为此,我想看看那里有什么键。

以下是我的尝试。但是我收到了一个错误

    my %tgs = (
        'articles' =>  {
                           'vim' => 'about vim',
                           'awk' => 'about awk',
                           'sed' => 'about sed'
                       },
        'ebooks'   =>  {
                           'linux 101'    => 'about linux',
                       }
    );

    foreach my $k (keys %tgs){
        print $k;
        print "\n";
        foreach my $k2 (keys %$tgs{$k}){ #<-----this is where perl is having a problem
            print $k2;
            print "\n";
        }
    }

syntax error at PATH line #, near "$tgs{"
syntax error at PATH line #, near "}"
Execution of PATH aborted due to compilation errors.

我的方法有什么问题?我的推理是因为$ tgs {$ k}返回哈希的引用,我可以为每个循环取消引用它,但我猜不是吗?

1 个答案:

答案 0 :(得分:7)

您需要$tgs{$k}周围的大括号:

foreach my $k2 (keys %{$tgs{$k}}){ #<-----this is where perl is having a problem

完整的代码是:

foreach my $k1 (keys %tgs){
    print "Key level 1: $k1\n";
    foreach my $k2 (keys %{$tgs{$k1}}) {
        print "    Key level 2: $k2\n";
    }
}