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

Don't re-invent the wheel. Use the "sort" command like this:
$ cat junk.txt AGCT:0:370:1 AGGT:3:52:1 TGAA:2:233:0 AGAG:0:32:0 $ sort -t: -k2,3 junk.txt AGAG:0:32:0 AGCT:0:370:1 TGAA:2:233:0 AGGT:3:52:1

Replies are listed 'Best First'.
Re^2: Sort a 2D array based on 2 columns
by masala_curry (Novice) on Apr 26, 2009 at 07:17 UTC
    Hello,
    I forgot to mention I am coding this thing in PERL. I wish to have a 2D array of all those values so that I may process the array further.
    I believe to do it in the elegant way you suggested, I would have to output that array in a file first- say junk.txt
    "System" command would help me with the "sort" command.
    I will again have to retrieve the sorted file and slurp it in an array once more.
    I really do not wish to have that overhead but if most would agree that this is the easiest way to go about it I would go ahead and use it.
      Code it in Perl then ...
      #!/usr/bin/perl -w use strict; my @mega = ( ["AGCT", "0", "370", "1"], ["AGGT", "3", "52", "1"], ["TGAA", "2", "233", "0"], ["AGAG", "0", "32", "0"] ); open ( fh, ">junk.txt" ); for my $row (@mega) { print fh (join ":", @{$row}) . "\n"; } close fh; my $shellout = <<`SHELL`; sort -n -t: -k2,4 junk.txt SHELL print "$shellout\n";
      ... if you expend some effort you can find away of avoiding writing the array to a file as sort does accept input form STDIN also, read the man page.
        How is this a great (or even good) solution? Sorting within perl is easier to read, understand, and is less code. It also doesn't require forking another process just to do something so simple as sorting.