如何在perl中正确创建和循环3D数组?

时间:2012-02-09 06:26:43

标签: arrays perl

我有一个算法可以选择3d数组中的单元格,然后读取或写入数据,这是对另一个3d数组的引用。将其视为“我的世界”算法。 问题是我不知道如何在Perl中创建一个像这样工作的数据结构:@ 3darray(x,y,z)= value 你能救我吗?

1 个答案:

答案 0 :(得分:7)

如果我理解正确:

use Data::Dumper;

my ($x, $y, $z) = (1, 2, 3);
my @array = map [map [map 0, 1..$z], 1..$y], 1..$x;

print Dumper \@array;

输出:

$VAR1 = [
          [
            [
              0,
              0,
              0
            ],
            [
              0,
              0,
              0
            ]
          ]
        ];

但是,没有必要事先建立这个结构,因为当您访问嵌套结构中的元素时,Perl会通过自动生成(参见下面的参考资料)为您创建它:

use Data::Dumper;

my @array;
$array[0][0][2] = 3;

print Dumper \@array;

输出:

$VAR1 = [
          [
            [
              undef,
              undef,
              3
            ]
          ]
        ];

来自perlglossary

autovivification

A Greco-Roman word meaning "to bring oneself to life". In Perl, storage locations
(lvalues) spontaneously generate themselves as needed, including the creation of
any hard reference values to point to the next level of storage. The assignment
$a[5][5][5][5][5] = "quintet" potentially creates five scalar storage locations,
plus four references (in the first four scalar locations) pointing to four new
anonymous arrays (to hold the last four scalar locations). But the point of
autovivification is that you don't have to worry about it.

至于循环,如果你需要索引:

for my $i (0 .. $#array) {
    for my $j (0 .. $#{$array[$i]}) {
        for my $k (0 .. $#{$array[$i][$j]}) {
            print "$i,$j,$k => $array[$i][$j][$k]\n";
        }
    }
}

否则:

for (@array) {
    for (@$_) {
        for (@$_) {
            print "$_\n";
        }
    }
}