Hello,

I have the following 2D array
my @megaMotif = ( ["AGCT", "0", "370", "1"], ["AGGT", "3", "52", "1"], ["TGAA", "2", "233", "0"], ["AGAG", "0", "32", "0"] );
The 2nd column may have numbers from 0 to 25. The third column will always be either 0 or 1.

I wish to sort this array by column 2nd as well as 4th!

This code sorts the array by 2nd column.
for $mega( sort{ $a->[1] <=> $b->[1] } @megaMotif ) { print @$mega; push (@megaMot, [@$mega]); }
The output of this would be:
"AGCT" "0" "370" "1"
"AGAG" "0" "32" "0"
"TGAA" "2" "233" "0"
"AGGT" "3" "52" "1"

The first two rows are sorted by 2nd column...but not by the 4th.

But this is the desired output:
"AGAG" "0" "32" "0"
"AGCT" "0" "370" "1"
"TGAA" "2" "233" "0"
"AGGT" "3" "52" "1"

Note the first two rows of the desired output.

Ofcourse, this is just a portion of the entire 2000 row array. How may I do this efficiently?

Kindly help.

In reply to 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.