如何在 Perl 中迭代 Hash(of Hashes)?

发布于 2024-08-23 15:33:50 字数 120 浏览 2 评论 0原文

我有哈希,其中键的值是其他哈希。

示例: {'key' =>; {'key2'=>; {'key3'=>; 'value'}}}

我如何迭代这个结构?

I have Hash where values of keys are other Hashes.

Example: {'key' => {'key2' => {'key3' => 'value'}}}

How can I iterate through this structure?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

药祭#氼 2024-08-30 15:33:50

这个答案建立在 Dave Hinton 背后的想法之上——即编写一个通用子例程来遍历哈希结构。这样的哈希遍历器获取代码引用并简单地为哈希中的每个叶节点调用该代码。

通过这种方法,同一个哈希遍历器可以用来做很多事情,具体取决于我们给它的回调。为了获得更大的灵活性,您需要传递两个回调 - 一个在值是哈希引用时调用,另一个在值是普通标量值时调用。 Marc Jason Dominus 的优秀著作 Higher Order Perl 更深入地探讨了此类策略。

use strict;
use warnings;

sub hash_walk {
    my ($hash, $key_list, $callback) = @_;
    while (my ($k, $v) = each %$hash) {
        # Keep track of the hierarchy of keys, in case
        # our callback needs it.
        push @$key_list, $k;

        if (ref($v) eq 'HASH') {
            # Recurse.
            hash_walk($v, $key_list, $callback);
        }
        else {
            # Otherwise, invoke our callback, passing it
            # the current key and value, along with the
            # full parentage of that key.
            $callback->($k, $v, $key_list);
        }

        pop @$key_list;
    }
}

my %data = (
    a => {
        ab => 1,
        ac => 2,
        ad => {
            ada => 3,
            adb => 4,
            adc => {
                adca => 5,
                adcb => 6,
            },
        },
    },
    b => 7,
    c => {
        ca => 8,
        cb => {
            cba => 9,
            cbb => 10,
        },
    },
);

sub print_keys_and_value {
    my ($k, $v, $key_list) = @_;
    printf "k = %-8s  v = %-4s  key_list = [%s]\n", $k, $v, "@$key_list";
}

hash_walk(\%data, [], \&print_keys_and_value);

This answer builds on the idea behind Dave Hinton's -- namely, to write a general purpose subroutine to walk a hash structure. Such a hash walker takes a code reference and simply calls that code for each leaf node in the hash.

With such an approach, the same hash walker can be used to do many things, depending on which callback we give it. For even more flexibility, you would need to pass two callbacks -- one to invoke when the value is a hash reference and the other to invoke when it is an ordinary scalar value. Strategies like this are explored in greater depth in Marc Jason Dominus' excellent book, Higher Order Perl.

use strict;
use warnings;

sub hash_walk {
    my ($hash, $key_list, $callback) = @_;
    while (my ($k, $v) = each %$hash) {
        # Keep track of the hierarchy of keys, in case
        # our callback needs it.
        push @$key_list, $k;

        if (ref($v) eq 'HASH') {
            # Recurse.
            hash_walk($v, $key_list, $callback);
        }
        else {
            # Otherwise, invoke our callback, passing it
            # the current key and value, along with the
            # full parentage of that key.
            $callback->($k, $v, $key_list);
        }

        pop @$key_list;
    }
}

my %data = (
    a => {
        ab => 1,
        ac => 2,
        ad => {
            ada => 3,
            adb => 4,
            adc => {
                adca => 5,
                adcb => 6,
            },
        },
    },
    b => 7,
    c => {
        ca => 8,
        cb => {
            cba => 9,
            cbb => 10,
        },
    },
);

sub print_keys_and_value {
    my ($k, $v, $key_list) = @_;
    printf "k = %-8s  v = %-4s  key_list = [%s]\n", $k, $v, "@$key_list";
}

hash_walk(\%data, [], \&print_keys_and_value);
峩卟喜欢 2024-08-30 15:33:50

这是你想要的吗? (未经测试)

sub for_hash {
    my ($hash, $fn) = @_;
    while (my ($key, $value) = each %$hash) {
        if ('HASH' eq ref $value) {
            for_hash $value, $fn;
        }
        else {
            $fn->($value);
        }
    }
}

my $example = {'key' => {'key2' => {'key3' => 'value'}}};
for_hash $example, sub {
    my ($value) = @_;
    # Do something with $value...
};

Is this what you want? (untested)

sub for_hash {
    my ($hash, $fn) = @_;
    while (my ($key, $value) = each %$hash) {
        if ('HASH' eq ref $value) {
            for_hash $value, $fn;
        }
        else {
            $fn->($value);
        }
    }
}

my $example = {'key' => {'key2' => {'key3' => 'value'}}};
for_hash $example, sub {
    my ($value) = @_;
    # Do something with $value...
};
蓝眼睛不忧郁 2024-08-30 15:33:50

这篇文章可能会有用。

foreach my $key (keys %hash) {
    foreach my $key2 (keys %{ $hash{$key} }) {
        foreach my $key3 (keys %{ $hash{$key}{$key2} }) {
            $value = $hash{$key}{$key2}->{$key3};
            # .
            # .
            # Do something with $value
            # .
            # .
            # .
        }
    }
}

This post may be useful.

foreach my $key (keys %hash) {
    foreach my $key2 (keys %{ $hash{$key} }) {
        foreach my $key3 (keys %{ $hash{$key}{$key2} }) {
            $value = $hash{$key}{$key2}->{$key3};
            # .
            # .
            # Do something with $value
            # .
            # .
            # .
        }
    }
}
忱杏 2024-08-30 15:33:50

前面的答案展示了如何推出您自己的解决方案,最好至少执行一次,这样您就可以了解 perl 引用和数据结构如何工作的本质。您绝对应该阅读 perldoc perldscperldoc perlref 如果您还没有。

但是,您不需要编写自己的解决方案 - CPAN 上已经有一个模块,它将为您迭代任意复杂的数据结构:数据::访客

The earlier answers show how to roll your own solution, which is good to do at least once so you understand the guts of how perl references and data structures work. You should definitely take a read through perldoc perldsc and perldoc perlref if you haven't already.

However, you don't need to write your own solution -- there is already a module on CPAN which will iterate through arbitrarily-complex data structures for you: Data::Visitor.

夜夜流光相皎洁 2024-08-30 15:33:50

这并不是一个真正的新答案,但我想分享如何做更多的事情
只需递归打印所有哈希值,但如果需要也可以修改它们。

这是我对 dave4420 答案的轻微修改,其中
该值作为参考传递给回调,所以我的回调
然后例程可以修改哈希中的每个值。

我还必须重建哈希,因为每个循环都会创建副本
不是参考文献。

sub hash_walk {
   my $self = shift;
    my ($hash, $key_list, $callback) = @_;
    while (my ($k, $v) = each %$hash) {
        # Keep track of the hierarchy of keys, in case
        # our callback needs it.
        push @$key_list, $k;

        if (ref($v) eq 'HASH') {
            # Recurse.
            $self->hash_walk($v, $key_list, $callback);
        }
        else {
            # Otherwise, invoke our callback, passing it
            # the current key and value, along with the
            # full parentage of that key.
            $callback->($k, \$v, $key_list);
        }

        pop @$key_list;
        # Replace old hash values with the new ones
        $hash->{$k} = $v;
    }
}

hash_walk(\%prj, [], \&replace_all_val_strings);

sub replace_all_val_strings {
    my ($k, $v, $key_list) = @_;
    printf "k = %-8s  v = %-4s  key_list = [%s]\n", $k, $v, "@$key_list";
    $v =~ s/oldstr/newstr/;
    printf "k = %-8s  v = %-4s  key_list = [%s]\n", $k, $v, "@$key_list";
}

This is not really a new answer but I wanted to share how to do more than
just print all the hash values recursively but also to modify them if needed.

Here is my ever so slight modification of the dave4420's answer in which
the value is passed to the callback as a reference so my callback
routine could then modify every value in the hash.

I also had to rebuild the hash as the while each loop creates copies
not references.

sub hash_walk {
   my $self = shift;
    my ($hash, $key_list, $callback) = @_;
    while (my ($k, $v) = each %$hash) {
        # Keep track of the hierarchy of keys, in case
        # our callback needs it.
        push @$key_list, $k;

        if (ref($v) eq 'HASH') {
            # Recurse.
            $self->hash_walk($v, $key_list, $callback);
        }
        else {
            # Otherwise, invoke our callback, passing it
            # the current key and value, along with the
            # full parentage of that key.
            $callback->($k, \$v, $key_list);
        }

        pop @$key_list;
        # Replace old hash values with the new ones
        $hash->{$k} = $v;
    }
}

hash_walk(\%prj, [], \&replace_all_val_strings);

sub replace_all_val_strings {
    my ($k, $v, $key_list) = @_;
    printf "k = %-8s  v = %-4s  key_list = [%s]\n", $k, $v, "@$key_list";
    $v =~ s/oldstr/newstr/;
    printf "k = %-8s  v = %-4s  key_list = [%s]\n", $k, $v, "@$key_list";
}
不回头走下去 2024-08-30 15:33:50

如果您使用 perl 作为“CPAN 解释器”,那么除了 Data::Visitor< /code>Data::Deep有一个超级简单的 Data::Traverse

use Data::Traverse qw(traverse);
 
my %test_hash = (
  q => [qw/1 2 3 4/],
  w => [qw/4 6 5 7/],
  e => ["8"],
  r => { 
         r => "9"  ,
         t => "10" ,
         y => "11" ,
      } ,
);

traverse { return if /ARRAY/; print "$a => $b\n" if /HASH/ && $b > 8 } \%test_hash;

输出

t => 10
y => 11

$a$b在此处被视为特殊变量(与sort()一样),而在<代码>traverse()函数。 Data::Traverse 是一个非常简单但非常有用的模块,没有非核心依赖项。

If you are using perl as a "CPAN interpreter" then in addition to Data::Visitor and Data::Deep there is the super simple Data::Traverse:

use Data::Traverse qw(traverse);
 
my %test_hash = (
  q => [qw/1 2 3 4/],
  w => [qw/4 6 5 7/],
  e => ["8"],
  r => { 
         r => "9"  ,
         t => "10" ,
         y => "11" ,
      } ,
);

traverse { return if /ARRAY/; print "$a => $b\n" if /HASH/ && $b > 8 } \%test_hash;

Output:

t => 10
y => 11

$a and $b are treated as special variables here (as with sort()) while inside the traverse() function. Data::Traverse is a very simple but immensely useful module with no non-CORE dependencies.

自控 2024-08-30 15:33:50

你必须循环它两次。 IE

while ( ($family, $roles) = each %HoH ) {
   print "$family: ";
   while ( ($role, $person) = each %$roles ) {
      print "$role=$person ";
   }
print "\n";
}

You will have to loop through it twice. i.e.

while ( ($family, $roles) = each %HoH ) {
   print "$family: ";
   while ( ($role, $person) = each %$roles ) {
      print "$role=$person ";
   }
print "\n";
}
甜味超标? 2024-08-30 15:33:50
foreach my $keyname (keys(%foo) {
  my $subhash = $foo{$keyname};
  # stuff with $subhash as the value at $keyname
}
foreach my $keyname (keys(%foo) {
  my $subhash = $foo{$keyname};
  # stuff with $subhash as the value at $keyname
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文