gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:56:29 38 4
gpt4 key购买 nike

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

使用临时变量和嵌套 map 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

最佳答案

如果你不再需要 $AoH,你可以使用破坏性的方式:

delete $_->{c} for @$AoH;

关于perl - 这是在 Perl 中提取 AoH 子集的最干净的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8112239/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com