in reply to Creating and Accessing 3-D array
If you used Data::Dump (or Data::Dumper) to display your datastructure, the reason becomes clear:
#! perl -slw use strict; use Data::Dump qw[ pp ]; my $col; my @col; my $row; my @row; my $sheet; my @sheet; for($col = 0; $col < 3; $col++) { push @col, "0";} for($row = 0; $row < 3; $row++) { push @row, [@col];} for($sheet = 0; $sheet < 3; $sheet++){push @sheet, [@row];} $sheet[0][1][2] = 5; pp \@sheet; __END__ c:\test>junk38 do { my $a = [ [[0, 0, 0], [0, 0, 5], [0, 0, 0]], ['fix', 'fix', 'fix'], ['fix', 'fix', 'fix'], ]; $a->[1][0] = $a->[0][0]; $a->[1][1] = $a->[0][1]; $a->[1][2] = $a->[0][2]; $a->[2][0] = $a->[0][0]; $a->[2][1] = $a->[0][1]; $a->[2][2] = $a->[0][2]; $a; }
The reason is this line:
for($sheet = 0; $sheet < 3; $sheet++){push @sheet, [@row];}
The [@row] does a deep copy of the contents of @row, but a shallow copy of the things contained within those contents. Hence, the same arrays appear as as subarrays of the higher levels. (That's not a good description, but the best I could come up with.)
Perhaps this corrected code will explain things better:
#! perl -slw use strict; use Data::Dump qw[ pp ]; my $col; my @col; my $row; my @row; my $sheet; my @sheet; for($col = 0; $col < 3; $col++) { push @col, "0";} for($row = 0; $row < 3; $row++) { push @row, [@col];} for($sheet = 0; $sheet < 3; $sheet++){ push @sheet, [ map [ @$_ ], @row ]; } $sheet[0][1][2] = 5; pp \@sheet; __END__ c:\test>junk38 [ [[0, 0, 0], [0, 0, 5], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], ]
And for reference, here's how I would initialise that construct:
#! perl -slw use strict; use Data::Dump qw[ pp ]; my @sheets = map { [ map { [ ( 0 ) x 3 ] } 1 .. 3 ] } 1 .. 3; $sheets[0][1][2] = 5; pp \@sheets; __END__ c:\test>junk38 [ [[0, 0, 0], [0, 0, 5], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], ]
Which I find more captures the operation and therefore easier to follow, but others might not agree.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Creating and Accessing 3-D array
by Anonymous Monk on Feb 06, 2011 at 13:43 UTC | |
|
Re^2: Creating and Accessing 3-D array
by Anonymous Monk on Feb 07, 2011 at 05:27 UTC |