cyrus_dlx has asked for the wisdom of the Perl Monks concerning the following question:

Hi, i have an array of hashes and need it sorted by one of the fields in the hash. For instance i build my structure this way:
my @people= (); my @names = qw(jack peter smith jason patrick sylvia randa debbie dian +e john gina solomon fances jojo kwame nana esi francis ato justice); for my $i (0 .. $#names) { my %hash = (); $hash{"age"} = int(rand 75) + 1; $hash{"name"} = $names[$i]; push (@people, \%hash); }
and for easy printing of what we got:
# some sort algorithm goes here @sorted = sort by_name @people; for $i (0 .. $#sorted) { my %person = %{$sorted[$i]}; print "$person{name} is $person{age} years old.\n"; }

Here i need @people sorted by either the "name" or "age" field. Any ideas are welcome
Thanks all!!

Replies are listed 'Best First'.
Re: Sorting an array of hashes by hash field
by holli (Abbot) on Apr 01, 2005 at 00:37 UTC
    @sorted=sort { $a->{name} cmp $b->{name} } @people;


    holli, /regexed monk/
Re: Sorting an array of hashes by hash field
by tlm (Prior) on Apr 01, 2005 at 00:43 UTC

    See this post. Using the nomenclature I used in that post:

    sub property { return $_[ 0 ]->{ name } } @sorted = map { $_->[ 0 ] } sort { $a->[ 1 ] cmp $b->[ 1 ] } map { [ $_, property( $_ ) ] } @people;
    See the post linked above for the details. If you really insist on the less efficient approach you outlined, then
    sub by_name { $a->{ name } cmp $b->{ name } }

    the lowliest monk

      Thanks for both responses, wow, didnt think it was that easy. I wouldnt have figured that out given a year. Thanks ;)
Re: Sorting an array of hashes by hash field
by Roy Johnson (Monsignor) on Apr 01, 2005 at 01:44 UTC