简体   繁体   English

如何从哈希散列中映射(和排序)值?

[英]How do I map (and sort) values from a hash of hashes?

I have a hash of hashes, like so: 我有一个哈希哈希,如下所示:

%hash = ( a  => { b => 1, c =>2, d => 3},
          a1 => { b => 11, c =>12, d => 13},
          a2 => { b => 21, c =>22, d => 23} )

I want to extract the "b" element and put it into an array. 我想提取“ b”元素并将其放入数组。 Right now, I am looping through the hash to do this, but I think I can improve efficiency slightly by using map instead. 现在,我正在遍历散列来执行此操作,但是我认为可以通过使用map来稍微提高效率。 I'm pretty sure that if this was an array of hashes, I'd use something like this: 我很确定,如果这是一个哈希数组,我会使用类似以下的方法:

@hasharray = ( { b => 1, c =>2, d => 3},
               { b => 11, c =>12, d => 13},
               { b => 21, c =>22, d => 23} )
@array = map { ($_->{b} => $_) } @hasharray

Forgive me if I'm wrong, I'm still learning how map works. 如果我错了,请原谅我,我仍在学习map的工作原理。 But what I'd like to know is how would I go about mapping the hash of hashes? 但是我想知道的是,我将如何映射散列的哈希? Is this even possible using map? 使用地图甚至可能吗? I have yet to find any examples of doing this. 我还没有找到任何这样做的例子。

Even better, the next step in this code is to sort the array once it's populated. 更好的是,此代码中的下一步是对数组进行填充后对其进行排序。 I'm pretty sure this is possible, but I'm not smart enough on using map to figure it out myself. 我很确定这是可能的,但是我对使用map自行解决还不够聪明。 How would I go about doing this all in one shot? 我将如何一次性完成所有这些工作?

Thanks. 谢谢。 Seth 赛斯

这将提取并排序所有“ b”:

my @array = sort { $a <=> $b } map $_->{b}, values %hash;

This fills @array with a sorted list of array references, each containing the value of b and the hashref it came from. 这会在@array填充数组引用的排序列表,每个列表都包含b的值和它来自的hashref。

my @array = sort {$$a[0] <=> $$b[0]}
            map  { [$$_{b} => $_] } 
            values %hash;

my @sorted_hashes = map {$$_[1]} @array;

Take your second solution, and substitute values %hash for @hasharray : 采取第二种解决方案,并将values %hash替换为@hasharray

@array = map { ($_->{b} => $_) } values %hash;

(And don't forget the ; to terminate the statement.) (并且不要忘记;来终止该语句。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM