[英]Sort hash by value and key (in that order)
I'm looking for a nice way to sort a hash in Perl by value first and by key afterwards. 我正在寻找一种很好的方法来首先按值排序Perl,然后按键排序。
Example: 例:
my %userids = (
williams => "Marketing",
smith => "Research",
johnson => "Research",
jones => "Marketing",
brown => "Marketing",
davis => "Research"
);
Output: 输出:
Marketing: brown
Marketing: jones
Marketing: williams
Research: davis
Research: johnson
Research: smith
Please note that value was the first sorting level. 请注意, 值是第一个排序级别。 Second sorting level is key . 第二个排序级别是关键 。 Any idea how to do this in an elegant and high-performance way? 知道如何以优雅和高性能的方式做到这一点吗? Thanks! 谢谢!
Good reference: http://www.misc-perl-info.com/perl-sort.html#shv 很好的参考: http : //www.misc-perl-info.com/perl-sort.html#shv
#!/usr/bin/perl
my %userids = (
williams => "Marketing",
smith => "Research",
johnson => "Research",
jones => "Marketing",
brown => "Marketing",
davis => "Research"
);
foreach (sort { ($userids{$a} cmp $userids{$b}) || ($a cmp $b) } keys %userids)
{
print "$_: $userids{$_}\n";
}
I would like to add one more thing, use \\L sequence
in sorting. 我想补充一点,在排序中使用\\L sequence
。
From Perlfaq4 : How do I sort a hash (optionally by value instead of key)? 从Perlfaq4 :我如何排序哈希(可选择按值而不是键)?
To make our report order case-insensitive, we use the \\L sequence
in a double-quoted string to make everything lowercase. 为了使我们的报表顺序不区分大小写,我们在双引号字符串中使用\\L sequence
使所有内容都小写。 The sort()
block then compares the lowercased values to determine in which order to put the keys. 然后sort()
块比较较低的值以确定放置键的顺序。
foreach (sort { $userids{$a} cmp $userids{$b} or "\L$a" cmp "\L$b" ) {
print "$_: $userids{$_}\n";
}
Output : 输出:
brown: Marketing
jones: Marketing
williams: Marketing
davis: Research
Johnson: Research # here 'J'ohnson, J is in uppercase(taking assumption), come as fifth record
smith: Research
2. 2。
foreach (sort { $userids{$a} cmp $userids{$b} or $a cmp $b ) {
print "$_: $userids{$_}\n";
}
Output: 输出:
brown: Marketing
jones: Marketing
williams: Marketing
Johnson: Research # here it shifted to fourth record
davis: Research
smith: Research
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.