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

Hi all, I need to keep the 3 littlest values in an array and their association with a name. The idea is the following: I have in a first step:
old[1]{john} = 1 old[2]{lucy} = 2 old[3]{marc} = 1
and I would like to have in a second step (after sorting on values)
old[1]{john} = 1 old[2]{marc} = 1 old[3]{lucy} = 2
But I did not find a way to do that. Would you have any idea, please? Best regards, Pandelis

Replies are listed 'Best First'.
Re: Array of Hashes and sorting by values
by Corion (Patriarch) on Jan 17, 2011 at 15:27 UTC

      Thank you for your answer.

      Following that I tried the following code:

      sub par_num { return $a <=> $b } $old[0]{jure} = 1; $old[1]{juge} = 1; $old[2]{pupe} = 3; $old[3]{mupe} = 2; @tri = sort par_num @old; @old = @tri; for $i ( 0 .. $#old ) { print "$i is { "; for $mot ( keys %{ $old[$i] } ) { print "$mot=$old[$i]{$mot} "; } print "}\n"; }

      It works well on simple array but not on array of hashes

        I guess you need to modify the code in par_num to actually return the number associated with the name, instead of doing a simple numerical comparison of the names.

        sub par_num { $a->{ (keys %$a)[0]} <=> $b->{ (keys %$b)[0]} };

        ... is untested but could do what you need.