我正在寻找一种很好的方法,可以按值先按键,然后按键对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
请注意,值是第一排序级别。第二排序级别是关键。知道如何以优雅和高性能的方式执行此操作吗?谢谢!
最佳答案
好的引用: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";
}