Re: sorting by multiple criterias (sub-sorting)
From: Steve Grazzini (grazz_at_pobox.com)
Date: 10/11/03
- Next message: Michael Budash: "Re: sorting by multiple criterias (sub-sorting)"
- Previous message: Cognition Peon: "Re: sorting by multiple criterias (sub-sorting)"
- In reply to: Tom Kirchner: "sorting by multiple criterias (sub-sorting)"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sat, 11 Oct 2003 17:13:52 GMT
Tom Kirchner <tokirc@gmx.net> wrote:
> Im currently writing on a part of a program where there is an
> array of hash-refs holding data. and I want to sort these
> array-elements (the hash-refs) by a first criteria and then
> another one.
There are two FAQs dealing with this topic:
% perldoc -q sort
> E.g. If each hash would be something like:
>
> @array = (
> { 'name' => 'dan', 'age' => '12', 'shoesize' => '34' },
Just a style nit:
{ name => 'dan', age => 12, shoesize => 34 },
> { 'name' => 'tom', 'age' => '19', 'shoesize' => '56' },
> { 'name' => 'tom', 'age' => '23', 'shoesize' => '43' },
> { 'name' => 'frank', 'age' => '42', 'shoesize' => '24' },
> # ...
> );
>
> what I want is: sorting first by 'name' and then, when there
> are multiple records with the same name, sorting this (sub)group
> by their 'age' and if there are records with the same
> name and same age, sorting these by their shoesize.
Quoting from "How do I sort an array by (anything)?"
If you need to sort on several fields, the following paradigm
is useful.
@sorted = sort { field1($a) <=> field1($b) ||
field2($a) cmp field2($b) ||
field3($a) cmp field3($b)
} @data;
This works because when two elements of the input list are
equal, the <=> and cmp operators will return zero (and the
sub will fall through to the next comparison).
To adapt it to your example, just substitute hash lookups for
the subroutine call.
@sorted = sort { $a->{name} cmp $b->{name} ||
$a->{age} <=> $b->{age} ...
-- Steve
- Next message: Michael Budash: "Re: sorting by multiple criterias (sub-sorting)"
- Previous message: Cognition Peon: "Re: sorting by multiple criterias (sub-sorting)"
- In reply to: Tom Kirchner: "sorting by multiple criterias (sub-sorting)"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|