如何从Perl中的多维数组中获取每个第一个元素?

时间:2014-09-08 10:14:40

标签: arrays perl multidimensional-array

我有一个多维(2D)@array

我编写了以下代码来获取每个嵌套数组中的第一个元素:

use strict;
use warnings;
use Data::Dumper;

my @array = (
    [ '/dev/vg00/lvol6', 114224,  46304,   67920,   '41%', '/home' ],
    [ '/dev/vg00/lvol7', 8340704, 4336752, 4003952, '52%', '/opt' ],
    [ '/dev/vg00/lvol4', 520952,  35080,   485872,  '7%',  '/tmp' ],
);

my @new_array;

foreach (@array) {
    push @new_array, @$_[0];
}

是否有更好或更快的方法(例如,使用map函数)生成一个新数组(嵌套数组中的每个第一个元素/值),并具有以下值:

$VAR1 = [
          '/dev/vg00/lvol6',
          '/dev/vg00/lvol7',
          '/dev/vg00/lvol4'
        ];

PS。对不起琐碎的问题,但今天(星期一早上)我今天脑子里一片空白。

2 个答案:

答案 0 :(得分:11)

使用map, and click here for the perldoc

use strict; 
use warnings;
use Data::Dumper;

my @array = (
             ['/dev/vg00/lvol6', 114224, 46304, 67920, '41%', '/home'],
             ['/dev/vg00/lvol7', 8340704, 4336752, 4003952, '52%', '/opt'],
             ['/dev/vg00/lvol4', 520952, 35080, 485872, '7%', '/tmp']
            );

my @new_array = map { $_->[0] } @array; 

print Dumper(\@new_array);

打印出来:

$VAR1 = [
      '/dev/vg00/lvol6',
      '/dev/vg00/lvol7',
      '/dev/vg00/lvol4'
    ];

答案 1 :(得分:3)

my @new_array = map $_->[0], @array;

虽然map可能不是更快的选项,

my @array = (
      ['/dev/vg00/lvol6', 114224, 46304, 67920, '41%', '/home'],
      ['/dev/vg00/lvol7', 8340704, 4336752, 4003952, '52%', '/opt'],
      ['/dev/vg00/lvol4', 520952, 35080, 485872, '7%', '/tmp']
);
sub umap {
  my @new_array = map $_->[0], @array;
  return;
}
sub ufor {
  my @new_array;
  foreach (@array) {
      push @new_array, $_->[0];
  }
  return;
}

use Benchmark qw( cmpthese ) ;
cmpthese( -5, {
    umap => \&umap,
    ufor => \&ufor,
});

结果

         Rate umap ufor
umap 691765/s   -- -14%
ufor 804475/s  16%   --