这是在Perl中提取AoH子集的最干净的方法吗?

Zai*_*aid 5 perl data-structures

出于好奇,是否有另一种方法可以提取我的AoH结构的子集?AoH是“矩形”的(即,保证所有哈希引用具有相同的键)。

map对于本质上是花哨的哈希片,使用temp var和nested s似乎有点过多:

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
Run Code Online (Sandbox Code Playgroud)

Mis*_*rEd 3

map这使用一个和任意的键列表来完成:

my @wantedKeys = qw/a b/;
my $wanted = [
    map { my %h; @h{@wantedKeys} = @{ $_ }{@wantedKeys}; \%h }  @$AoH
];
Run Code Online (Sandbox Code Playgroud)

(在这篇文章的一点帮助下)