Reputation: 96274
Say I build the following multidimensional array:
my @array; # don't need the empty list
my @other_array = (0 ... 10);
foreach my $i ( 0 .. 10 ) {
$array[$i] = [ @other_array[1..$#other_array] ];
}
I would like to collect a "column" of this multidimensional array into a separate array,
For example, if I want to collect the items in the first column, I would like something like
my @other_array = ();
@other_array = $array[:][1]; # This does NOT work in Perl
Is there a way to do this in Perl without looping?
Eventually what I want to do is get the array of max
of each column of my multidimensional array.
PS: This question is inspired by this other question: Building and printing a multidimensional list in Perl without looping.
Upvotes: 1
Views: 2858
Reputation: 8895
For your example, this might be an overkill solution, but assuming your are planing to do this with huge multi-dimensional arrays (matrix's), use PDL
and do a transpose
then slice out the desired line.
Upvotes: 2
Reputation: 37146
Befriend map
:
my @other_array = map $array[$_][1], 0 .. $#array;
The Slices section in perldoc perllol
has more examples.
Upvotes: 4
Reputation: 3995
I think you want:
my @other_array = map { $_->[1] } @array;
Another language might have a special syntax for this operation, but it would still be performing a loop under the hood.
Upvotes: 5