如何按哈希值之一对哈希引用数组进行排序? [英] How do I sort an array of hash references by one of the hash values?

查看:172
本文介绍了如何按哈希值之一对哈希引用数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,请原谅我生锈的Perl.我正在尝试修改Bugzilla的"whine.pl",以生成按严重性排序的错误列表.

First, please pardon my rusty Perl. I'm trying to modify Bugzilla's "whine.pl" to generate lists of bugs sorted by severity.

因此它给了我一个哈希引用数组.每个哈希包含一堆有关特定错误的信息(ID,受让人,严重性等).我想按严重性对数组进行排序.最好的方法是什么?

So it gives me an array of hash references. Each hash contains a bunch of information about a particular bug (id, assignee, severity, etc). I want to sort the array by severity. What's the best way to do this?

我想出了两种可能性.一种是创建五个数组(每个严重级别一个),然后遍历该数组并将哈希引用推入适当的严重级别数组.之后,我可以重新组装它们,并用已排序的数组替换原始数组.

I'd come up with a couple of possibilities. One is to create five arrays (one for each level of severity), then loop over the the array and push the hash refs into the appropriate severity level array. After this, I could reassemble them and replace the original array with the sorted one.

我的朋友想出的另一种方法是将严重性级别(以文本形式存储在哈希中)分配给一些数字小键盘,然后将其cmp.也许是这样的吗?

Another way that my friend came up with would be to assign the severity levels (stored as text in the hashes) to some nubmers, and cmp them. Maybe something like this?

sub getVal {
    my $entry = $_[0];
    %lookup = ( "critical" => 0, ... );
    return $lookup(entry("bug_severity"));
}
@sorted = sort { getVal($a) <=> getVal($b) } @unsorted;

推荐答案

我喜欢您提出的解决方案:

I like your proposed solution:

my %sevs = (critical => 0, high => 1, ...);
my @sorted = sort { $sevs{$a->{bug_severity}} <=> $sevs{$b->{bug_severity}} } @unsorted

这篇关于如何按哈希值之一对哈希引用数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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