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

Alb*_*lby 1 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.
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*scu 7

你需要括号$tgs{$k}:

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

完整的代码是:

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