【发布时间】:2016-04-06 06:22:54
【问题描述】:
我尝试以树的形式打印哈希键和值。我的 perl 代码如下。
use strict ;
use warnings ;
my %hash = (
first => {
a => "one",
b => "two",
c => "three",
},
second => {
d => "four",
e => "five",
f => "six",
},
third => "word",
);
foreach my $line (keys %hash) {
print "$line: \n";
foreach my $elem (keys %{$hash{$line}}) {
print " $elem: " . $hash{$line}->{$elem} . "\n";
}
}
输出错误信息: 第二: d:四个 f:六 e:五个 第三: 在 C:\Users\Dell\Music\PerlPrac\pracHash\hshofhsh_net.pl 第 19 行使用“strict refs”时,不能使用字符串(“word”)作为 HASH ref。
这里,在第三个键值下不打印。我该怎么做?
【问题讨论】:
-
因为
$hash{third}的值不是hashref,所以%{$hash{third}}是抛出错误。你可以使用if (ref $hash{$line} eq "HASH") ...