这是一个更长、更冗余的解决方案,实际上更像是一个练习。但是您可能会发现以这种方式检查哈希迭代的结构很有趣。(我知道我知道!)如果您只有主哈希名称 ( %gates_info
),并且没有任何键,这可能很有用。这就是你的问题所暗示的情况。这会拉出与哈希一样深的所有键和值名称,以防其中任何一个可能有用。我还上传了一个工作示例。(请注意,这确实需要知道您的哈希有多少层。)
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my %gates_info=(
'order' => {
'nand' => {
'nand2_1' =>2,
'nand2_5' =>-1,
'nand2_4' =>2,
'nand2_6' =>-1,
'nand2_2' =>2,
'nand2_3' =>3
},
'and' => {
'and2'=>1,
'and3'=>2,
},
}
);
print Dumper %gates_info;
print "\n\n";
my @gate;
my $hival;
foreach my $gate (sort keys %gates_info) {
foreach my $gatekey (sort keys %{$gates_info{$gate}}) {
foreach my $deepkey (sort keys %{$gates_info{$gate}{$gatekey}}) {
my $deepvalue = $gates_info{$gate}->{$gatekey}->{$deepkey};
push @gate, $deepvalue;
@gate = sort @gate;
$hival = $gate[@gate - 1];
print "Gate is $gate, gatekey is $gatekey, deepkey is $deepkey, deepvalue is $deepvalue\n";
}
print "\nGatekey is $gatekey, highest value is $hival\n\n";
@gate = (); #empty gate array
}
}
exit 0;
代码的输出是:
$VAR1 = 'order';
$VAR2 = {
'and' => {
'and2' => 1,
'and3' => 2
},
'nand' => {
'nand2_3' => 3,
'nand2_6' => -1,
'nand2_4' => 2,
'nand2_5' => -1,
'nand2_2' => 2,
'nand2_1' => 2
}
};
Gate is order, gatekey is and, deepkey is and2, deepvalue is 1
Gate is order, gatekey is and, deepkey is and3, deepvalue is 2
Gatekey is and, highest value is 2
Gate is order, gatekey is nand, deepkey is nand2_1, deepvalue is 2
Gate is order, gatekey is nand, deepkey is nand2_2, deepvalue is 2
Gate is order, gatekey is nand, deepkey is nand2_3, deepvalue is 3
Gate is order, gatekey is nand, deepkey is nand2_4, deepvalue is 2
Gate is order, gatekey is nand, deepkey is nand2_5, deepvalue is -1
Gate is order, gatekey is nand, deepkey is nand2_6, deepvalue is -1
Gatekey is nand, highest value is 3