Out of curiosity, is there another way to extract a subset of my AoH structure? The AoH is 'rectangular' (i.e. guaranteed to have the same keys across all hashrefs).
The use of a temp var and nested map
s seems a bit too much for what is essentially a fancy hash slice:
use strict;
use warnings;
use Data::Dump 'dump';
my $AoH = [ # There are many more keys in the real structure
{ a => "0.08", b => "0.10", c => "0.25" },
{ a => "0.67", b => "0.85", c => "0.47" },
{ a => "0.06", b => "0.57", c => "0.84" },
{ a => "0.15", b => "0.67", c => "0.90" },
{ a => "1.00", b => "0.36", c => "0.85" },
{ a => "0.61", b => "0.19", c => "0.70" },
{ a => "0.50", b => "0.27", c => "0.33" },
{ a => "0.06", b => "0.69", c => "0.12" },
{ a => "0.83", b => "0.27", c => "0.15" },
{ a => "0.74", b => "0.25", c => "0.36" },
];
# I just want the 'a's and 'b's
my @wantedKeys = qw/ a b /; # Could have multiple unwanted keys in reality
my $a_b_only = [
map { my $row = $_;
+{
map { $_ => $row->{$_} } @wantedKeys
}
}
@$AoH
];
dump $a_b_only; # No 'c's here
This does it with one map
and an arbitrary list of keys:
my @wantedKeys = qw/a b/;
my $wanted = [
map { my %h; @h{@wantedKeys} = @{ $_ }{@wantedKeys}; \%h } @$AoH
];
(With a little help from this post)
If you do not need $AoH anymore, you can use the destructive way:
delete $_->{c} for @$AoH;
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