in reply to Array of Hashes and sorting by values

This is a FAQ. See perlfaq4 on "How do I sort an array by (anything)?".

  • Comment on Re: Array of Hashes and sorting by values

Replies are listed 'Best First'.
Re^2: Array of Hashes and sorting by values
by pandelis (Initiate) on Jan 17, 2011 at 20:00 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.

        Your code works !

        Thank you very much !