develooper Front page | perl.beginners | Postings from February 2002

Re: Sorting an array of hashes

Thread Previous | Thread Next
From:
Brett W. McCoy
Date:
February 6, 2002 11:38
Subject:
Re: Sorting an array of hashes
Message ID:
Pine.LNX.4.43.0202061429220.17062-100000@chapelperilous.net
On Wed, 6 Feb 2002, Tomasi, Chuck wrote:

> Does anyone have any clever ideas for sorting an array of hashes based on
> a key such as an ID number?
>
> Example:
>
> @AoH = (
> 	{ ID => 10101, UserID => 1041, Status => 2 },
>         { ID => 10541, UserID => 1211, Status => 1 },
>         { ID => 10111, UserID => 1211, Status => 2 },
>         { ID => 10721, UserID => 1198, Status => 1 }
> );

This is quite similar to the question posed earlier about sorting on an
element of an anonymous array in a hash:

my @AoH = (
		   { ID => 10101, UserID => 1041, Status => 2 },
		   { ID => 10541, UserID => 1211, Status => 1 },
		   { ID => 10111, UserID => 1211, Status => 2 },
		   { ID => 10721, UserID => 1198, Status => 1 }
		   );

my @ID = ();

foreach(@AoH) { push @ID, $_->{ID} }

my @result = sort {$a <=> $b} @ID;

foreach(@result) {

	print "$_\n";
}

-- Brett

                                          http://www.chapelperilous.net/
------------------------------------------------------------------------
"Seed me, Seymour"
-- a random number generator meets the big green mother from outer space


Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About