【问题标题】:Attempting to Iterate over hash of hash in perl. What's wrong with this approach?尝试在 perl 中迭代散列的散列。这种方法有什么问题?
【发布时间】:2012-10-24 22:36:31
【问题描述】:

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

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

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

【问题讨论】:

    标签: perl hash foreach


    【解决方案1】:

    $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";
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-23
      • 1970-01-01
      • 2017-05-08
      • 2013-09-10
      • 2013-07-19
      • 1970-01-01
      • 2011-03-13
      • 1970-01-01
      相关资源
      最近更新 更多