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

Hi Monks, I've a array of hashes containing the data in the below format:
@array = ( {'key1' ==> 'abc', 'key2' ==> '111', 'key3' ==> 'abcdef'}, {'key1' ==> 'acc', 'key2' ==> '101', 'key3' ==> 'abcdef'}, {'key1' ==> 'acc', 'key2' ==> '1000', 'key3' ==> 'abcdef'}, {'key1' ==> 'abc', 'key2' ==> '112', 'key3' ==> 'abcdef'} )
I want to sort the above array of hashes based on multiple keys in hashes. i.e., If I do a sort as key1-ASC, key2-DSC, the output of the above array should be like this
{'key1' ==> 'abc', 'key2' ==> '112', 'key3' ==> 'abcdef'}, {'key1' ==> 'abc', 'key2' ==> '111', 'key3' ==> 'abcdef'}, {'key1' ==> 'acc', 'key2' ==> '1000', 'key3' ==> 'abcdef'}, {'key1' ==> 'acc', 'key2' ==> '101', 'key3' ==> 'abcdef'}
Hope the above illustration is understandable. This kind of multi-column sorting is already available in MsExcel. i.e., if we have data in 2 columns and then sort them by specifying - "sort first column in ascending" and "sort second column in descending", it will give the above output. Please let know, if this can be done in PERL. Thanks in advance. Mani.

Replies are listed 'Best First'.
Re: MsExcel like Multi Column Sorting
by davorg (Chancellor) on Dec 01, 2006 at 11:27 UTC

    From perlfaq4 - How do I sort an array by (anything)?:

    If you need to sort on several fields, the following paradigm is useful.

    @sorted = sort { field1($a) <=> field1($b) || field2($a) cmp field2($b) || field3($a) cmp field3($b) } @data;

    (Also, it's "Perl", not "PERL")

    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

      To apply this code to the data structure as given by the op, this gives:
      @sorted = sort { $a->{key2} cmp $b->{key2} || $a->{num1} <=> $b->{num1} || $a->{key3} cmp $b->{key3} || } @data;
      Note that to sort descending for one column, just swap $a and $b in the comparison expression, for that column.
    A reply falls below the community's threshold of quality. You may see it by logging in.