基于Perl中哈希值排序的简单方法 [英] The simple way to sort based on values in a hash in perl

查看:142
本文介绍了基于Perl中哈希值排序的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常可以根据键进行排序,然后迭代哈希,如下所示:

Normally sorting based on keys and then iterating a hash can be done as following:

for $k (sort (keys %h)) {
  print $k, $h{$k};
}

但是如何基于值进行排序,然后遍历哈希呢?我可以考虑通过交换键和值对来创建新的哈希.但是还有其他更聪明的方法吗?

But how to do the sorting based on values and then iterate through the hash? I can think of creating a new hash by swapping the key and value pairs. But is there any more clever way of doing this?

非常感谢.

推荐答案

如果希望排序比较器不是cmp,则可以提供代码块或子例程作为sort的第一个参数.有关更多详细信息,请参见文档.

If you want the sort comparator to be something other than cmp, you can supply a code block or a subroutine as the first parameter to sort. See the documentation for more details.

my %h = (
    aaaa => 'z',
    bbb  => 'x',
    c    => 'y',
);

# Sort on hash values.
for my $k (sort {$h{$a} cmp $h{$b}} keys %h) {
    print $k, "\n";   # bbb c aaaa
}

# Sort using a named subroutine.
for my $k (sort by_length keys %h) {
    print $k, "\n";   # c bbb aaaa
}

sub by_length {
    length($a) <=> length($b);
}

这篇关于基于Perl中哈希值排序的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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