The Schwartzian transform is the classic way to do this. First transform your multi-dimensional array to a list of key/reference pairs where the key is some hash of the values you want to sort on (a unique hash is best :) and the reference is a reference to the row the key pertains to. Then sort the pairs by the key. Finally pull the rows out and you're done.

use strict; use warnings; my @chrnums = ( [qw(chr1 10)], [qw(chr3 20)], [qw(chr1 30)], [qw(chr3 5)], [qw(chr5 5)], ); @chrnums = map { #Extract sorted rows $_->[1] } sort {$a->[0] cmp $b->[0]} map { #Transform to keys and refs [(sprintf "%5d%5d", $_->[0] =~ /(\d+)/, $_->[1]), $_] } @chrnums; print "$_->[0] $_->[1]\n" for @chrnums;

Prints:

chr1 10 chr1 30 chr3 5 chr3 20 chr5 5

DWIM is Perl's answer to Gödel

In reply to Re: Sorting a two-dimensional array by two columns by GrandFather
in thread Sorting a two-dimensional array by two columns by a11

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.