in reply to Selecting Ranges of 2-Dimensional Data
use warnings; use strict; #use Data::Dump qw/pp/; use Test::More tests=>2; sub arr_alias { \ @_ } # arr_ref to list of aliases sub getsubset { my ( $data, $range ) = @_; my ( $rows, $cols ) = @$range; # [y0,y1], [x0,x1] # YMMV! return [ map { arr_alias @$_[ $cols->[0] .. $cols->[1] ] # x-slice } @$data[ $rows->[0] .. $rows->[1] ] # y-slice ]; } my $data = [ ['a','b','c','d'], ['e','f','g','h'], ['i','j','k','l'], ['m','n','o','p'] ]; my $range = [ [1,2], [1,2] ]; # or any other useful syntax! my $subset = getsubset($data, $range); is_deeply $subset, [ ['f','g'], ['j','k'] ]; # Part 2: $subset->[0][1] = 'X'; $subset->[1][0] = 'Y'; is_deeply $data, [ ['a','b','c','d'], ['e','f','X','h'], ['i','Y','k','l'], ['m','n','o','p'] ];
C:/Perl_524/bin\perl.exe d:/tmp/matrix_range.pl 1..2 ok 1 ok 2
Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery
FootballPerl is like chess, only without the dice
simplified code, added comments
changed from slices to ranges
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Selecting Ranges of 2-Dimensional Data
by haukex (Archbishop) on Oct 27, 2018 at 07:36 UTC | |
by LanX (Saint) on Oct 27, 2018 at 15:15 UTC | |
by haukex (Archbishop) on Oct 28, 2018 at 09:16 UTC | |
by LanX (Saint) on Oct 28, 2018 at 10:17 UTC | |
by haukex (Archbishop) on Oct 28, 2018 at 10:58 UTC | |
| |
by Aldebaran (Curate) on Oct 30, 2018 at 20:51 UTC | |
by haukex (Archbishop) on Oct 30, 2018 at 22:54 UTC | |
by Aldebaran (Curate) on Nov 01, 2018 at 21:05 UTC |