1

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

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

    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} 返回哈希的引用,我可以在每个循环中取消引用它,但我猜不是?

4

1 回答 1

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";
    }
}
于 2012-11-05T05:10:07.537 回答