我试图找到一种方法在同一个循环中打印一对哈希数组的子哈希值。
这就是我的哈希的样子:
$VAR1 = {
'countrya' => [
[ { 'area' => 'statea', 'population' => '10' },
{ 'area' => 'stateb', 'population' => '20' } ], # previous
[ { 'area' => 'statea', 'population' => '30' },
{ 'area' => 'stateb', 'population' => '40' } ] # current
],
'countryb' => [
[ { 'area' => 'statec', 'population' => '50' },
{ 'area' => 'stated', 'population' => '60' } ], # previous
[ { 'area' => 'statec', 'population' => '70' },
{ 'area' => 'stated', 'population' => '80' } ] # current
]
}
这是我希望实现的结果:
countrya
*****
statea -> 10
statea -> 30
stateb -> 20
stateb -> 40
countryb
*****
statec -> 50
statec -> 70
stated -> 60
stated -> 80
countrya
和countryb
中的第一个子数组表示先前的值,而第二个数组表示当前值。因此,必须在另一个之后打印这些值。
到目前为止,我已经设法通过此循环获得了我想要的输出:
foreach my $h (keys %countries) {
print "$h\n";
foreach my $i ($countries{$h}) {
print "$$i[0][0]{'area'} -> ";
print "$$i[0][0]{'population'}\n";
print "$$i[1][0]{'area'} -> ";
print "$$i[1][0]{'population'}\n";
print "$$i[0][1]{'area'} -> ";
print "$$i[0][1]{'population'}\n";
print "$$i[1][1]{'area'} -> ";
print "$$i[1][1]{'population'}\n";
}
}
但是,上面的代码只能假设每个数组中只有两个子数。我应该如何修改代码以支持任意数量的subhashes?