brucezepplin brucezepplin - 1 month ago 6
Perl Question

access / print nth element of sub array, for every array

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 to I access say the 1st sub element of every sub array? something akin to
multarray[*][0]
so produce:

"one"
4
"alpha"


Thanks!

Answer

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);

__END__

$VAR1 = [
          'one',
          4,
          'alpha'
        ];

See also: perldsc