如何循环遍历哈希数组的Perl数组?

San*_*ing 3 arrays perl hash

我想打印一个哈希数组数组,所以我查看了perldsc,最后得到了

for my $j (0 .. $#aoaoh) {
    for my $aref (@aoaoh) {
    print '"' . join('","', @$aref[$j]), "\"\n";
    }
}
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

有谁知道如何做到这一点?

Dav*_*oss 8

它就像你走了一样有效.在程序中添加一些测试数据可以为我们提供:

#!/usr/bin/perl

use strict;
use warnings;

my @aoaoh = (
    [
        { a => 1, b => 2 },
        { c => 3, d => 4 },
    ],
    [
        { a => 101, b => 102 },
        { c => 103, d => 104 },
    ],
);

for my $j (0 .. $#aoaoh) {
    for my $aref (@aoaoh) {
    print '"' . join('","', @$aref[$j]), "\"\n";
    }
}
Run Code Online (Sandbox Code Playgroud)

并运行,给出:

$ ./aoaoh 
"HASH(0x9c45818)"
"HASH(0x9c70c48)"
"HASH(0x9c60418)"
"HASH(0x9c70c08)"
Run Code Online (Sandbox Code Playgroud)

所以你已经成功地导航了两个级别的数组,你只需要使用散列引用来解除引用.也许这样的东西:

#!/usr/bin/perl

use strict;
use warnings;

my @aoaoh = (
    [
        { a => 1, b => 2 },
        { c => 3, d => 4 },
    ],
    [
        { a => 101, b => 102 },
        { c => 103, d => 104 },
    ],
);

for my $j (0 .. $#aoaoh) {
    for my $aref (@aoaoh) {
        # print '"' . join('","', @$aref[$j]), "\"\n";
        for (keys %{$aref->[$j]}) {
            print "$_ -> $aref->[$j]{$_}\n";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这使:

$ ./aoaoh 
a -> 1
b -> 2
a -> 101
b -> 102
c -> 3
d -> 4
c -> 103
d -> 104
Run Code Online (Sandbox Code Playgroud)

就个人而言,我会这样写,因为我认为处理元素比索引更容易.

#!/usr/bin/perl

use strict;
use warnings;

my @aoaoh = (
    [
        { a => 1, b => 2 },
        { c => 3, d => 4 },
    ],
    [
        { a => 101, b => 102 },
        { c => 103, d => 104 },
    ],
);

for my $aref (@aoaoh) {
    for my $href (@$aref) {
        for (keys %{$href}) {
            print "$_ -> $href->{$_}\n";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)