出于好奇,还有另一种方法来提取我的AoH结构的子集吗? AoH是“矩形”(即保证在所有hashref上具有相同的键)。
使用temp var和嵌套map
对于基本上是花哨的哈希切片来说似乎有点太多了:
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
答案 0 :(得分:2)
如果你不再需要$ AoH,你可以使用破坏性的方式:
delete $_->{c} for @$AoH;
答案 1 :(得分:2)
这是一个map
和一个任意的键列表:
my @wantedKeys = qw/a b/;
my $wanted = [
map { my %h; @h{@wantedKeys} = @{ $_ }{@wantedKeys}; \%h } @$AoH
];
(在this post)的帮助下
答案 2 :(得分:1)
您想要delete
。
my $foo = [ map { delete $_->{c}; $_ } @$AoH ];
如果要保留原始数据,则需要先取消引用哈希值。
my $foo = [ map { my %hash = %$_; delete $hash{c}; \%hash; } @$AoH ];
答案 3 :(得分:1)
这是我的解决方案(让我介绍一下很好的Data :: Printer模块):
use Modern::Perl;
use Data::Printer { colored => 1 };
my $AoH = [
{ 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, so I build a new hash with the keys I want
my @ab = map { {a=>$_->{a}, b=>$_->{b}} } @$AoH;
p @ab;
# If you don't mind remove the "c" key in your original structure:
# map { delete $_->{c} } @$AoH;
# and $AoH is an array of hashes without the "c" key.