从multidemsional数组中提取列

时间:2015-04-23 12:40:07

标签: perl

我有一个多维数组

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

我想提取一个单维数组:

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

这些是对@multi [0] [1],@ multi [1] [1],@ multi [2] [1] ...

的引用的组合

我该怎么做?

4 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:2)

例如,您可以这样做:

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;

输出:

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

答案 2 :(得分:1)

数组数组

perldoc perllolman perllolperldoc.perl.org/perllol.html

对此进行了详细说明

您可以取消引用您的数组变量:

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

同一事物的另一种语法:

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

尝试:

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

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

将呈现:

$other = [[1,undef,'A'],[2,['first','second','third'],'B']];
哪里...
$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";

可以给出:

1
2
first
third
B

答案 3 :(得分:0)

您需要使用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";

输出: first second third