# Solved: Perl -- Sorting a muti-dimensional array by 2 columns



## andynic (May 25, 2007)

Hi,

The code below produces the following output:
before
x ... a ... 3
i ... b ... 2
9 ... a ... 1
a ... a ... 2
a ... b ... 1
after
x ... a ... 3
9 ... a ... 1
a ... a ... 2
i ... b ... 2
a ... b ... 1

What I want to do is to sort by column 1 (the middle column) and within that then by column 2.
That is, I want to produce this output:
after
9 ... a ... 1
a ... a ... 2
x ... a ... 3
a ... b ... 1
i ... b ... 2

What syntax do I need to use to replace the line that sorts the array?
Namely: @arr = sort { $a->[1] cmp $b->[1] } @arr;

use strict;

my @arr = ();

$arr[0][0] = "x"; $arr[0][1] = "a"; $arr[0][2] = "3";
$arr[1][0] = "i"; $arr[1][1] = "b"; $arr[1][2] = "2";
$arr[2][0] = "9"; $arr[2][1] = "a"; $arr[2][2] = "1";
$arr[3][0] = "a"; $arr[3][1] = "a"; $arr[3][2] = "2";
$arr[4][0] = "a"; $arr[4][1] = "b"; $arr[4][2] = "1";

print "before\n";
for (my $i=0; $i<=$#arr; $i++) { print "$arr[$i][0] ... $arr[$i][1] ... $arr[$i][2]\n"; }

@arr = sort { $a->[1] cmp $b->[1] } @arr; ###<<<<< What syntax do I need here?

print "after\n";
for (my $i=0; $i<=$#arr; $i++) { print "$arr[$i][0] ... $arr[$i][1] ... $arr[$i][2]\n"; }

exit;


----------



## andynic (May 25, 2007)

Problem Solved:
Found the solution with the help of a friend who is a Perl guru.
The syntax is:
@arr = sort { $a->[1] cmp $b->[1] || $a->[2] cmp $b->[2] } @arr;
Andynic


----------

