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

how can i sort on a file named $file with three columns (numeric, numeric, string) and i want to first sort the third column and then reverse sort the second column numerically without disordering the sort done on the third column?

Replies are listed 'Best First'.
Re: Sorting on different fields
by Aristotle (Chancellor) on Jul 23, 2002 at 01:24 UTC
    You want a custom sort function. Assuming you have a list of lists in @record, the following would do the job: my @sorted = sort { $a->[2] cmp $b->[2] || $b->[1] <=> $a->[1] } @record; It uses cmp on to compare the third elements of each record, and if they turn out to be identical, uses <=> to compare the second elements of each record in reverse order.

    Makeshifts last the longest.

Re: Sorting on different fields
by mkmcconn (Chaplain) on Jul 23, 2002 at 03:07 UTC
      sorry, i'm new to perl, so if some of the questions are obvious, i apologize.....what's the purpose of these 2 lines?
      map {$_->[0]} map { $_ ,/(\w+)\s+(\w+)\s+(\w+)/} <DATA>

      Edit by tye

        The second line creates an array for each element of the input list; its elements are the entire input string ($_) in the first element, and the first three words of the input (pulled out using the parens in the pattern match) in the next elements. The first line then later goes and pulls that first element containing the entire string back out of these arrays. Check out perldoc -f map to understand how it works.

        Makeshifts last the longest.

        There is nothing obvious about what's going on there, rchou2. Although it solves your problem (I think), it's not a very good answer because it's hard to explain and to understand. That's nothing in my favor - I can't immediately think of the way I would have done it before learning this trick.

        Read more about the Schwartzian Transform to understand it. Especially, try to understand why it changes everything to remove the square brackets as you did in your cut and paste (you need them, to create the temporary arrays that are being used for sorting).
        mkmcconn