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"


In reply to Re: Sort a 2D array based on 2 columns by perliff
in thread Sort a 2D array based on 2 columns by masala_curry

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.