I have a multidimensional (2D) @array.
I wrote following code to get the first element from the every nested 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];
}
Is there a better or faster way (for example, with using the map function) to produce a new array (every first element/value from the nested array) with following values:
$VAR1 = [
'/dev/vg00/lvol6',
'/dev/vg00/lvol7',
'/dev/vg00/lvol4'
];
PS. I'm sorry for trivial question, but today (in the monday morning) I've a big blank out in my head today.
Use 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);
This prints out:
$VAR1 = [
'/dev/vg00/lvol6',
'/dev/vg00/lvol7',
'/dev/vg00/lvol4'
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With