in reply to Slice of a multidimensional array
There are two way of looking at what constitutes a slice of a 2d array--and more for higher dimensions:)
In the first veiw, the result is what you would get if you could notionally extend perl's @arr[n..m] syntax to a 2D array: @arr[*][n..m] which might be described as "Give me a new 2d array where each row consists of just the columns n through m of the original array". For your example array, and with n & m set to 1 & 2 respectively, this would result in
my @vslice = (['b','c'], ['i','j'], ['y','z']);
The second view, and the one you want, is where the resultant arrays row(s) become 1 (or more) column(s) from the original array. for the same example as above you get
my @yxslice = ( ['b','i','y'], ['c','j','z'] );
Two functions to produce these
#! perl -slw use strict; use Data::Dumper; sub vslice { map{ [ @{$_}[@_] ] } @{+shift}; } sub yxslice { my $aref = shift; map{ my $i=$_; [ map{ $_->[$i] } @$aref ] } @_; } my @arr = (['a','b','c','d'], ['h','i','j','k'], ['w','x','y','z']); my @vslice = vslice \@arr, 1..2; print Dumper \@vslice; my @yxslice = yxslice \@arr, 1..2; print Dumper \@yxslice; __END__ C:\test>240941 $VAR1 = [ [ 'b', 'c' ], [ 'i', 'j' ], [ 'x', 'y' ] ]; $VAR1 = [ [ 'b', 'i', 'x' ], [ 'c', 'j', 'y' ] ];
I would use these versions of the two functions as it simplifies the syntax of using them slightly, but prototypes are almost universally condemned.
sub vslice (\@@) { map{ [@{$_}[@_]] } @{+shift}; } sub yxslice (\@@) { my $aref = shift; map{ my $i=$_; [ map{ $_->[$i] } @$aref ] } @_; }
|
|---|