Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the cleanest way to extract an AoH subset in Perl?

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 maps 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
like image 955
Zaid Avatar asked Nov 13 '11 14:11

Zaid


2 Answers

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)

like image 169
MisterEd Avatar answered Oct 05 '22 11:10

MisterEd


If you do not need $AoH anymore, you can use the destructive way:

delete $_->{c} for @$AoH;
like image 31
choroba Avatar answered Oct 05 '22 09:10

choroba