Reputation: 9752
I have a multidimensional array:
@multarray = ( [ "one", "two", "three" ],
[ 4, 5, 6, ],
[ "alpha", "beta", "gamma" ]
);
I can access @multarray[0]
[
[0] [
[0] "one"
[1] "two"
[2] "three"
]
]
or even @multarray[0][0]
"one"
But, how do I access say the 1st sub element of every sub array? Something akin to multarray[*][0]
to produce:
"one"
4
"alpha"
Upvotes: 2
Views: 581
Reputation: 62106
You can use map and dereference each array:
use warnings;
use strict;
use Data::Dumper;
my @multarray = (
[ "one", "two", "three" ],
[ 4, 5, 6, ],
[ "alpha", "beta", "gamma" ]
);
my @subs = map { $_->[0] } @multarray;
print Dumper(\@subs);
Output:
$VAR1 = [
'one',
4,
'alpha'
];
See also: perldsc
Upvotes: 8
Reputation: 9296
Using a for()
loop, you can loop over the outer array, and use any of the inner elements. In this example, I've set $elem_num
to 0
, which is the first element. For each loop over the outer array, we take each element (which is an array reference), then, using the $elem_num
variable, we print out the contents of the inner array's first element:
my $elem_num = 0;
for my $elem (@multarray){
print "$elem->[$elem_num]\n";
}
Upvotes: 3