我只是在学习perl.
我试图使用临时变量重写这个多级循环,这样我就不需要以前的键($key1 $key2)来获取对$key3的访问(解除引用).这样做最简单的方法是什么.谢谢.
for my $key1 ( keys %foo ) { for my $key2 ( keys %{$foo{$key1}} ) { for my $key3 ( keys %{$foo{$key1}{$key2}} )
解决方法
你可以使用while和each这样:
while (my ($key1,$inner_hash) = each %foo) { while (my ($key2,$inner_inner_hash) = each %$inner_hash) { while (my ($key3,$value) = each %$inner_inner_hash) { print $value; } } }
此方法使用的内存少于foreach键%hash,后者在开始迭代之前构造哈希中所有键的列表.每种方法的缺点是您无法指定排序顺序.有关详细信息,请参阅documentation.