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

时间:2010-09-16 10:42:57

标签: arrays perl hash

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

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

但它不起作用。

有谁知道怎么做?

4 个答案:

答案 0 :(得分: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";
    }
}

然后运行:

$ ./aoaoh 
"HASH(0x9c45818)"
"HASH(0x9c70c48)"
"HASH(0x9c60418)"
"HASH(0x9c70c08)"

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

#!/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";
        }
    }
}

给出了:

$ ./aoaoh 
a -> 1
b -> 2
a -> 101
b -> 102
c -> 3
d -> 4
c -> 103
d -> 104

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

#!/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";
        }
    }
}

答案 1 :(得分:1)

foreach my $aoh (@aoaoh) {

    foreach my $hashref ( @{$aoh} ) {

        foreach my $key ( keys %{$hashref} ) {

            print $key . " => " . $hashref->{$key}, "\n";
        }

        print "#" x 40, "\n";
    }
}

更新:抱歉,它必须是数组(不是数组引用)

答案 2 :(得分:1)

循环遍历整个套件&堆

use 5.012;
use warnings;

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

for my $root (@array) {
    for my $each_array_of_hashes (@$root) {
        for my $k (keys %{ $each_array_of_hashes } ) {
            say $k, ' => ', $each_array_of_hashes->{$k};
        }
    }
}

这就是你要追求的吗?

答案 3 :(得分:1)

看看 perlreftut ,它会对你有帮助, 并看到下面的答案。

  #!/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[$j]}) {
            for my $test (keys %{$aref})
            {
               print"$test => ${$aref}{$test}\n";
            }
        }
    }

输出:

a => 1
b => 2
c => 3
d => 4
a => 101
b => 102
c => 103
d => 104