PERL Sorting

Randal L. Schwartz merlyn at
Wed Nov 28 17:32:52 CST 2001

>>>>> "Aaron" == Aaron Kilbey <kilbey at> writes:

Aaron> I'm trying to do a sort where one array gets sorted by two other arrays, one
Aaron> after another.
Aaron> I have:
Aaron> @fileArray = @fileArray[sort { $temp1[$a] <=> $temp1[$b] } 0..$#temp1];
Aaron> This sorts @fileArray by the values in @temp1.
Aaron> If I now do:
Aaron> @fileArray = @fileArray[sort { $temp2[$a] <=> $temp2[$b] } 0..$#temp2];
Aaron> I have sorted @fileArray by @temp2 yet I lose my first sort results
Aaron> defeating the purpose.
Aaron> I'm guesssing I have to compound the sorts but I'm not sure where the "or"
Aaron> goes with this notation?

Can you explain what you want?  Is it a two-level sort, with @temp1
being the primary sort order, and @temp2 being the secondary sort order
to break ties in the primary?  If so, use this:

    @fileArray = @fileArray[sort {
      $temp1[$a] <=> $temp1[$b] or $temp2[$a] <=> $temp2[$b]
    } 0..$#temp1];

Aaron> Basically looking for:
Aaron> Location    IQ
Aaron> ---------------------
Aaron> Astoria      10
Aaron> Astoria      40
Aaron> Astoria      100
Aaron> Portland    10
Aaron> Portland    40
Aaron> Portland    100
Aaron> @temp1 being locations, @temp2 being ages.

Oops.. if you have strings, one of those <=> needs to be "cmp" instead.

Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn at> <URL:>
Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
See for onsite and open-enrollment Perl training!

More information about the Pdx-pm-list mailing list