Subject: | BUG: multi-field numerical sort |
Date: | Tue, 15 Sep 2009 15:42:29 -0500 |
To: | bug-template-toolkit [...] rt.cpan.org |
From: | "Felipe Gasper (cPanel)" <felipe [...] cpanel.net> |
If I numerically sort a set of data like:
my @data = (
{ foo: 22, bar: 128 },
{ foo: 22, bar: 23 },
);
....in Template Toolkit using the following:
[% data.nsort('foo', 'bar') %]
....what TT will return is a sort on these strings:
22/*^UNLIKELY^*/128
22/*^UNLIKELY^*/23
....which will not match the desired behavior of numerically sorting.
To fix:
Instead of making a single sort key, have it iterate through the fields
thus when sorting:
sub list_nsort {
my ($list, @fields) = @_;
return $list unless @$list > 1; # no need to sort 1 item lists
return [
@fields
? sort { first { $a->{$_} <=> $b->{$_} } @fields }
@$list
: sort { $a <=> $b }
@$list,
];
}
(In fact, might this be a better way to sort alphanumerically as well?)
-FG
--
Felipe Gasper
Linux/BSD development
cPanel of Texas, LLC
3701 Kirby Dr., suite 428
Houston, TX 77098
office 713-529-0800 x4096
cell 832-633-8092
fax 713-559-3206