SystemicPlural
SystemicPlural

Reputation: 5789

Extract a column from a multidemsional array

I have a multidimensional array

my @multi = ( [ 1, "first", "a" ], [ 2, "second", b ], [ 3, "third", c] ... );

I want to extract a single dimensional array of:

[ "first", "second", "third" ... ]

These would be a combination of the references to @multi[0][1], @multi[1][1] , @multi[2][1] ...

How do I do this?

Upvotes: 1

Views: 648

Answers (4)

F. Hauri  - Give Up GitHub
F. Hauri - Give Up GitHub

Reputation: 70822

Array of array

This is fully explained at perldoc perllol, man perllol or perldoc.perl.org/perllol.html

You could dereference your array variable:

map { ${$_}[1] } @multi

Another syntax for the same thing:

map { $_->[1] } @multi

try:

my @multi = ( [ 1, "first", "a" ], [ 2, "second", b ], [ 3, "third", c] );
print join(", ", map { ${ $_ }[1] } @multi)."\n";
print join(", ", map { $_->[1] } @multi)."\n";

And

use Data::Dumper;
my @multi = ( [ 1, "first", "a" ], [ 2, "second", b ], [ 3, "third", c] );
my @other=( [ 1 , undef , "A" ] , [ 2 , [ map { ${$_}[1] } @multi ], "B" ] );
$Data::Dumper::Indent= 0;
print Data::Dumper->Dump([\@other],[qw|other|])."\n";

will render:

$other = [[1,undef,'A'],[2,['first','second','third'],'B']];
Where...
$other = [[1,undef,"A"],[2,["first","second","third"],"B"]];
print $other->[0]->[0]."\n";
print $other->[1]->[0]."\n";
print $other->[1]->[1]->[0]."\n";
print $other->[1]->[1]->[2]."\n";
print $other->[1]->[2]."\n";

could give:

1
2
first
third
B

Upvotes: 1

mbsingh
mbsingh

Reputation: 489

You need to use de-reference:

my @multi = ( [ 1, "first", "a" ], [ 2, "second", b ], [ 3, "third", c]);
my $index = 0;
my @single;
foreach (@multi) {
    my $aref = $multi[$index];
    $single[$index] = $aref->[1];
    $index++;
}
print "\n @single \n";

Output: first second third

Upvotes: 0

zb226
zb226

Reputation: 10500

For example, you might do it like this:

use strict;

my @multi = ( [ 1, "first", "a" ], [ 2, "second", "b" ], [ 3, "third", "c" ] );
my $res;

push @$res, $_->[1] for @multi;

use Data::Dump;
dd $res;

Output:

["first", "second", "third"]

Upvotes: 2

ikegami
ikegami

Reputation: 385897

[ map { $_->[1] } @multi ]

Upvotes: 8

Related Questions