2012-02-09 39 views
2

我有一个算法,选择一个3D数组中的单元格,然后读取或写入数据,这是另一个3D数组的引用。把它想象成一个“我的世界”算法。 问题是我不知道如何在Perl中创建一个像这样的数据结构:@ 3darray(x,y,z)= value 你能帮我吗?如何在perl中正确创建和循环三维数组?

+2

体素的世界复制大块会在Perl数据语言(PD)中轻而易举L)。但是,PDL使用c样式数组而不是列表列表。 – zpmorgan 2012-02-10 06:01:09

+0

这是一个很好的发现,我会研究它。 – AlfredoVR 2012-02-10 17:19:32

回答

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"; 
     } 
    } 
} 
+0

谢谢你,今天没有得到RTFM很棒,但你给了我一个很好的答案。另外,如果我只是存储一个新的3D数组的引用,我会这样做? $ outer [$ x] [$ y] [$ z] =([] [$ x2] [$ y2] [$ z2] = $ value); ?是的,这有点疯狂:P – AlfredoVR 2012-02-09 08:02:31

+0

是否意味着有效地使'@ outer'成为6D阵列或将另一个3D数组深层复制到'@ outer'? – flesk 2012-02-09 08:30:24

+0

我已经使用这种方法解决了它,只是存储了一个新的3D数组的参考。 – AlfredoVR 2012-02-09 08:48:14

相关问题