如何在值上对Perl哈希排序并相应地对键排序(可能在两个数组中)? [英] How can I sort a Perl hash on values and order the keys correspondingly (in two arrays maybe)?

查看:53
本文介绍了如何在值上对Perl哈希排序并相应地对键排序(可能在两个数组中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Perl中,我想按数值对哈希键进行数字排序:

In Perl, I want to sort the keys of a hash by value, numerically:

{
  five => 5
  ten => 10
  one => 1
  four => 4
}

产生两个数组:

(1,4,5,10) and (one, four, five, ten)

然后我要对values数组进行规范化,以使数字是连续的:

And then I want to normalize the values array such that the numbers are sequential:

(1,2,3,4)

我该怎么做?

推荐答案

首先按关联值对键进行排序.然后获取值(例如,使用哈希切片).

First sort the keys by the associated value. Then get the values (e.g. by using a hash slice).

my @keys = sort { $h{$a} <=> $h{$b} } keys(%h);
my @vals = @h{@keys};

或者,如果您有哈希引用.

Or if you have a hash reference.

my @keys = sort { $h->{$a} <=> $h->{$b} } keys(%$h);
my @vals = @{$h}{@keys};

这篇关于如何在值上对Perl哈希排序并相应地对键排序(可能在两个数组中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆