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

I'm getting myself increasingly confused at how to go about this, so some assistance is greatly appreciated.

One piece of my latest program populates an array of hashes, each hash has multiple key/value pairs.

What I want to do after populating the array is:
- sort the array based on the value of 1 key
- if 2 or more elements have the same value of that key (values will be numeric), sort just those elements by the value of a 2nd key (without altering the sort order of the other elements in the array)

Sorting the array by the value of key is easy enough, but how to sort only some elements conditionally has me all kerfuffled. I've been reading up on Schwartzian Transforms, which I'm still not sure are applicable here.

Any advice (preferably with code samples) would be greatly appreciated.

Thanks in advance.

  • Comment on sorting array of hashes using multiple keys conditionally

Replies are listed 'Best First'.
Re: sorting array of hashes using multiple keys conditionally
by ikegami (Patriarch) on Dec 05, 2009 at 17:54 UTC

    Not two sorts. One sort with a properly crafted compare function.

    @a = sort { $a->{key1} <=> $b->{key1} || $a->{key2} <=> $b->{key2} } @a;

    I've been reading up on Schwartzian Transforms, which I'm still not sure are applicable here.

    It's not. It's used to minimize the cost of expensive compares (e.g. if I/O is done) when sorting long lists.

      I'm wondering why || doesn't cause a precedence problem here? I use "or" like below in this situation.

      update: looked up precedence table and spaceship (<=>) and cmp have much higher priority than I thought, so I guess this is ok either way.

      @a = sort { $a->{key1} <=> $b->{key1} or $a->{key2} <=> $b->{key2} } @a;
        I'm wondering why || doesn't cause a precedence problem here?

        Because the  || operator has lower precedence than the comparison operators like  <=> for example.    See perlop.

      Thanks, I've tried it and it does exactly what I'm looking for. Much simpler than I thought.
Re: sorting array of hashes using multiple keys conditionally
by GrandFather (Saint) on Dec 05, 2009 at 23:06 UTC

    Advice you want? "Never go against a Sicilian when death is on the line" or maybe "Show us a sample".

    Although you've been given the answer you were seeking, in general we can give better assistance if you show us what you have tried and the result you expect.


    True laziness is hard work