按值和键排序哈希(按此顺序)

时间:2011-10-17 09:44:20

标签: perl sorting hash

我正在寻找一种很好的方法,首先按值排序Perl,然后按键排序。

示例:

 my %userids = (
  williams => "Marketing",
  smith    => "Research",
  johnson  => "Research",
  jones    => "Marketing",
  brown    => "Marketing",
  davis    => "Research"
);

输出:

Marketing: brown
Marketing: jones
Marketing: williams
Research: davis
Research: johnson
Research: smith

请注意是第一个排序级别。第二个排序级别是 key 。知道如何以优雅和高性能的方式做到这一点吗?谢谢!

2 个答案:

答案 0 :(得分:27)

好参考: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";
}

答案 1 :(得分:7)

我想再添加一件事,在排序中使用\L sequence

来自 Perlfaq4 :如何对哈希进行排序(可选择按值而不是键)?

为了使我们的报表顺序不区分大小写,我们在双引号字符串中使用\L sequence来使所有内容都小写。然后sort()块比较小写值以确定放置键的顺序。

foreach (sort { $userids{$a} cmp $userids{$b} or "\L$a" cmp "\L$b" )  {
    print "$_: $userids{$_}\n"; 
} 

输出:

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

foreach (sort { $userids{$a} cmp $userids{$b} or $a cmp $b )  {
    print "$_: $userids{$_}\n"; 
}

输出:

brown: Marketing
jones: Marketing
williams: Marketing
Johnson: Research # here it shifted to fourth record
davis: Research
smith: Research