in reply to Sort a 2D array based on 2 columns

This is a FAQ. See perlfaq4 or perldoc -q sort:

Found in /usr/local/lib/perl5/5.10.0/pod/perlfaq4.pod
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;

Change that to use references and you're done.

Replies are listed 'Best First'.
Re^2: Sort a 2D array based on 2 columns
by doug (Pilgrim) on Apr 26, 2009 at 18:48 UTC

    While this complicated sort function does work, if there is a lot of data, it is faster to precompute a sort key for each row, and sort using that. The Schwartzian Transform is the standard name for this, and you should read up on it. It is also in perlfaq4.

    The general form of the ST is

    @sorted = map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [$_, foo($_)] } @unsorted;

    where foo() does whatever is necessary to make a sortable key. Obviously it is very specific to the data that you are working with. In your case the second column is an integer, and the fourth is either a 0 or a 1, so I'd go with something like

    sub foo($) { $_[0]->[1] . "." . $_[0]->[3]; }

    which will produce a single real number that you can compare using the <=> operator.