[英]Perl Sort a hash by value in descending order and then key in ascending order
Suppose I have a hash like假设我有一个 hash 之类的
%hash =
{
husky => 2
alaska => 2
akita => 3
brand =>1
}
How can I sort it by descending value(number), and ascending key(alphabet)?如何按降序值(数字)和升序键(字母)对其进行排序? The desired result should be:期望的结果应该是:
{
akita =>3
alaska =>2
husky =>2
brand=>1
}
A hash in Perl is not ordered nor it can be ordered. Perl 中的 hash 未订购也无法订购。 This is because the hash algorithm will spread the keys at random.这是因为hash算法会随机传播密钥。 A hash is defined like this: hash 定义如下:
my %hash = (
key1 => value1,
key2 => value2,
);
That is, it is defined with a list of value pairs key => value
.也就是说,它是用值对key => value
的列表定义的。 If you want a collection of ordered items, you need to use a list.如果你想要一个有序项目的集合,你需要使用一个列表。 It is defined like:它的定义如下:
my @list = ( 1, 2, 3 );
You may define a list of hash refs (closer to what you want) like this:您可以像这样定义 hash 参考列表(更接近您想要的):
my @list = (
{ key1 => value1 },
{ key2 => value2 },
);
A hash ref is a reference to a hash, and it is defined with {
and }
. hash ref 是对 hash 的引用,它由{
和}
定义。
So solving your problem, we have:因此,解决您的问题,我们有:
use Data::Dumper;
my %hash = (
husky => 2,
alaska => 2,
akita => 3,
brand =>1,
);
my @list = map { { $_ => $hash{$_} } }
sort { $hash{$b} <=> $hash{$a} or $a cmp $b }
keys %hash;
print Dumper(@list);
keys %hash
will give you a list of the keys in the hash. keys %hash
将为您提供 hash 中的键列表。 sort
will sort elements in a list. sort
将对列表中的元素进行排序。 As we want a special ordering, we provide the body of the sorting bit using the operators <=>
to compare numbers and cmp
to compare strings.由于我们想要一个特殊的排序,我们提供了排序位的主体,使用操作符<=>
来比较数字和cmp
来比较字符串。 Each returns -1
if the left side is less than the right side;如果左侧小于右侧,则每个返回-1
; 0
if they are the same and 1
if the left side is more than the right side.如果它们相同,则为0
,如果左侧多于右侧,则为1
。 The or
will enter the second comparison if the first is 0
.如果第一个是0
, or
将进入第二个比较。
Finally, map
will transform the list of keys (ordered) into a list of hash refs.最后, map
会将键列表(有序)转换为 hash 参考列表。
Dumper
is a function that creates a human readable text representation of any Perl data structure. Dumper
是一个 function,它创建任何 Perl 数据结构的人类可读文本表示。
The final output is:最终的 output 为:
$VAR1 = {
'akita' => 3
};
$VAR2 = {
'alaska' => 2
};
$VAR3 = {
'husky' => 2
};
$VAR4 = {
'brand' => 1
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.