如何打印哈希的匿名哈希

时间:2014-09-06 09:00:30

标签: perl

我正在尝试打印哈希的匿名哈希但没有获得所需的输出

$hash = { 
           name => { 
               nitesh => mine, 
               ankush => yours
           }, 
           Company => { 
               XYZ => mine, 
               other => sector_32
           }
};


foreach $key (sort keys %$hash) {
    print "\n key is $key";
    foreach $key2 (sort keys %{$hash=>{$key}}) {
        print "\n key2 is $key2";
    }
}

输出

 key is Company
 key2 is Company
 key is name
 key2 is name

1 个答案:

答案 0 :(得分:5)

当您使用=>时,您正在使用->来获取内部哈希的键。请记住引用哈希的值并将use strict; use warnings;添加到脚本的顶部:

use strict;
use warnings;

my $hash = { 
    name => {nitesh => 'mine', ankush => 'yours'}, 
    Company => { XYZ => 'mine', other => 'sector_32'} 
};


foreach my $key (sort keys %$hash) {
    print "key is $key\n";
    foreach my $key2 (sort keys %{$hash->{$key}}) {
        print "key2 is $key2\n";
    }
}

输出:

key is Company
key2 is XYZ
key2 is other
key is name
key2 is ankush
key2 is nitesh
相关问题