尝试在perl中打印混合哈希元素
我尝试以树的形式打印哈希键和值。下面给出了我的perl代码尝试在perl中打印混合哈希元素,perl,hash,Perl,Hash,我尝试以树的形式打印哈希键和值。下面给出了我的perl代码 use strict ; use warnings ; my %hash = ( first => { a => "one", b => "two", c => "three", }, second => { d => "four", e => "fiv
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\prachish\hshofhsh\u net.pl第19行使用“strict refs”时,无法将字符串(“word”)用作哈希引用
这里,第三个键下的值不打印。我该怎么做?您不能取消对字符串的引用(
$hash{third}
,即word
)。您可以使用ref
测试特定标量是否为引用:
for my $line (keys %hash) {
print "$line: \n";
if ('HASH' eq ref $hash{$line}) {
for my $elem (keys %{ $hash{$line} }) {
print " $elem: $hash{$line}{$elem}\n";
}
} else {
print " $hash{$line}\n";
}
}
因为
$hash{third}
的值不是hashref,所以%{$hash{third}}
抛出了一个错误。您可以使用if(ref$hash{$line}eq“hash”)…