First, please pardon my rusty Perl. I'm trying to modify Bugzilla's "whine.pl" to generate lists of bugs sorted by severity.
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 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.
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;
To avoid calling getVal more times than necessary, you can use "decorate, sort, undecorate". Decorate is getting the information you actually care about for the sort:
my @decorated = map { [ $_, getVal($_) ] } @unsorted;
Then sort the decorated list:
my @sortedDecorate = sort { $a->[1] <=> $b->[1] } @decorated;
Then get the original information back (undecorate):
my @sorted = map { $_->[0] } @sortedDecorate;
Or the more Perl-ish way to do it:
@sorted = map { $_->[0] }
sort { $a->[1] <=> $b->[1] }
map { [ $_, getVal($_) ] } @unsorted;