在 Perl 中遍历多维散列 [英] Traversing a multi-dimensional hash in Perl
本文介绍了在 Perl 中遍历多维散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果您在 perl 中有一个具有多个维度的散列(或对散列的引用),并且您想遍历所有值,那么最好的方法是什么.换句话说,如果我们有$f->{$x}{$y},我想要类似
If you have a hash (or reference to a hash) in perl with many dimensions and you want to iterate across all values, what's the best way to do it. In other words, if we have $f->{$x}{$y}, I want something like
foreach ($x, $y) (deep_keys %{$f})
{
}
代替
foreach $x (keys %f)
{
foreach $y (keys %{$f->{$x})
{
}
}
推荐答案
这是一个选项.这适用于任意深度的散列:
Here's an option. This works for arbitrarily deep hashes:
sub deep_keys_foreach
{
my ($hashref, $code, $args) = @_;
while (my ($k, $v) = each(%$hashref)) {
my @newargs = defined($args) ? @$args : ();
push(@newargs, $k);
if (ref($v) eq 'HASH') {
deep_keys_foreach($v, $code, \@newargs);
}
else {
$code->(@newargs);
}
}
}
deep_keys_foreach($f, sub {
my ($k1, $k2) = @_;
print "inside deep_keys, k1=$k1, k2=$k2\n";
});
这篇关于在 Perl 中遍历多维散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文