Slices
If you want to access a slice (part of a row) of a multidimensional array, you’re going to have to do some fancy subscripting. The pointer arrows give us a nice way to access a single element, but no such convenience exists for slices. You can always use a loop to extract the elements of your slice one by one:
@part = ();
for ($y = 7; $y < 13; $y++) {
push @part, $AoA[4][$y];
}This particular loop could be replaced with an array slice:
@part = @{ $AoA[4] } [ 7..12 ];If you want a two-dimensional slice, say,
with $x running from 4..8 and $y from 7..12, here’s one way to do it:
@newAoA = ();
for ($startx = $x = 4; $x <= 8; $x++) {
for ($starty = $y = 7; $y <= 12; $y++) {
$newAoA[$x – $startx][$y – $starty] = $AoA[$x][$y];
}
}In this example, the individual values within our destination
two-dimensional array, @newAoA,
are assigned one by one, taken from a two-dimensional subarray of
@AoA. An alternative is to create
anonymous arrays, each consisting of a desired slice of an @AoA subarray, and then put references to
these anonymous arrays into @newAoA. We would then be writing
references into @newAoA
(subscripted once, so to speak) instead of subarray values into a
twice-subscripted @newAoA. This
method eliminates the innermost loop:
for ($x = 4; $x <= 8; $x++) {
push @newAoA, [ @{ $AoA[$x] } [ 7..12 ] ];
}Of course, if you do this often, you should probably write a
subroutine called something like extract_rectangle. And if you do it very often with large collections of multidimensional ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access