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

use the CPAN module Sort::Fields. However, instead of having your data in a 2d array, sort:fields will sort if you have data that is tab delimited, each row in a separate array element. so if you have a tab-delimited file say data.txt with your data like this...
AGCT 0 370 1 AGAG 0 32 0 TGAA 2 233 0 AGGT 3 52 1
you can read in your data directly and sort. no need to make a 2d array...
use strict; # before anything else use Sort::Fields; use Data::Dumper; open(INP,"data.txt") || die "where's the file eh?"; my @data=<INP>; chomp (@data); # remove new line characters print "before sorting...\n"; print Dumper @data; #sort the data on the 2nd and the 4th field #this is numeric sort, as indicated by the "n" my @sorted = fieldsort '\t', [ '2n', '4n' ], @data; print "after sorting...\n"; print Dumper @sorted;
This produces the following output...
before sorting... $VAR1 = 'AGCT 0 370 1'; $VAR2 = 'AGAG 0 32 0'; $VAR3 = 'TGAA 2 233 0'; $VAR4 = 'AGGT 3 52 1'; after sorting... $VAR1 = 'AGAG 0 32 0'; $VAR2 = 'AGCT 0 370 1'; $VAR3 = 'TGAA 2 233 0'; $VAR4 = 'AGGT 3 52 1';
If you want to reverse sort, numerically, use a "-2n", for reverse numeric sorting by the second column. leaving out the "n" makes a alphanumeric sort. There are a number of examples in the module doc. I particularly like this as it is very flexible and provides the same kind of sorting power that you get using the unix sort, that has also been suggested in this thread.

perliff

----------------------

"with perl on my side"

Replies are listed 'Best First'.
Re^2: Sort a 2D array based on 2 columns
by AnomalousMonk (Archbishop) on Apr 26, 2009 at 09:06 UTC
    Note that the loop
        foreach my $ele (@data) {chomp $ele}
    is the same as the statement
        chomp(@data);
      thanks for the tip! saves me a lot of typing. I changed the code.

      perliff

      ----------------------

      "with perl on my side"