Perl 打印散列的散列名称或散列等
所以我有大量的散列Perl 打印散列的散列名称或散列等,perl,hash,hash-of-hashes,Perl,Hash,Hash Of Hashes,所以我有大量的散列 $VAR1 = { 'Peti Bar' => { 'Mathematics' => 82, 'Art' => 99, 'Literature' => 88 }, 'Foo Bar' => {
$VAR1 = {
'Peti Bar' => {
'Mathematics' => 82,
'Art' => 99,
'Literature' => 88
},
'Foo Bar' => {
'Mathematics' => 97,
'Literature' => 67
}
};
我在网上找到了一个例子
我想打印的是“小吧”和“富吧”,但不是那么简单。想象数学是散列中自己的散列,等等。所以我想打印“小条”->“数学”->“另一个散列”
“Foo Bar”->“文学”->“另一个哈希”
我想我要问的可能是打印散列的散列,而不打印每个散列的键/值。最简单的方法可能是使用递归函数遍历顶级散列和任何子散列,在进入子散列之前打印具有子散列的任何键:
#!/usr/bin/env perl
use strict;
use warnings;
use 5.010;
my %bighash = (
'Peti Bar' => {
'Mathematics' => {
'Arithmetic' => 7,
'Geometry' => 8,
'Calculus' => 9,
},
'Art' => 99,
'Literature' => 88
},
'Foo Bar' => {
'Mathematics' => 97,
'Literature' => 67
}
);
dump_hash(\%bighash);
sub dump_hash {
my $hashref = shift;
my @parents = @_;
return unless $hashref && ref $hashref eq 'HASH';
for my $key (sort keys %$hashref) {
my $val = $hashref->{$key};
next unless ref $val eq 'HASH';
say join ' -> ', @parents, $key;
dump_hash($val, @parents, $key);
}
}
输出:
Foo Bar
Peti Bar
Peti Bar -> Mathematics
与Dave S
use strict;
my $VAR1 = {
'Peti Bar' => {
'Mathematics' => 82,
'Art' => 99,
'Literature' => 88
},
'Foo Bar' => {
'Mathematics' => 97,
'Literature' => 67
}
};
sub printHash($$) {
my $hashRef = shift;
my $indent = shift;
for (keys %$hashRef) {
if (ref($hashRef->{$_}) eq 'HASH') {
print "$indent$_ \n";
printHash($hashRef->{$_},"\t$indent");
}
else {
print "$indent$_ $hashRef->{$_}\n";
}
}
}
printHash($VAR1,undef);
输出为:
Foo Bar
Mathematics 97
Literature 67
Peti Bar
Literature 88
Mathematics 82
Art 99
>>