[VPM] sort array of anon hashes

Peter Scott Peter at PSDT.com
Wed Oct 10 17:47:53 PDT 2007


At 04:38 PM 10/10/2007, Jer A wrote:
>say I have an array of hashes pushed like so : push(@array, {key1 => 
>'test', string => 'this is a string', id => '1'});
>
>how do i sort this alphabetically ascending or descending, by a 
>specified key val, and still preserve the anonymous hash
>
>eg. after sorting, $array[$i]->{key1} and  $array[$i]->{string} should 
>be both from the same anon hash entry in the array.

What do you want to sort it on?

Sorting won't change the data, only its order.  If you want to change 
the order of the hashrefs in the array based upon the value of key1 
then you can do:

   @array = sort { $a->{key1} cmp $b->{key1} } @array

There's no way sorting the array could break apart the entries in the 
hashrefs.
-- 
Peter Scott
Pacific Systems Design Technologies
http://www.perldebugged.com/
http://www.perlmedic.com/



More information about the Victoria-pm mailing list