=pod B sort_matrix( $matrix, [[$n1, $stringQ, $directionQ], [$n2, $stringQ, $directionQ], ...]) sorts a matrix by $n1 th column then $n2 th...and so on. $matrix must be a reference to references of arrays, having the form [[$n1, $n2,...], [...], ...]. $stringQ is a boolean indicating the corresponding column is a string or not. $directionQ is a boolean indicating ascending sort or not for the correpsonding column. Important: Index counting starts at 0. Example: my $ref_matrix = [ [3, 99, 'b'], [2, 77, 'c'], [1, 66, 'a'] ]; # sort by third column, then second column. sort_matrix( $ref_matrix, [ [2,1,1], [1,0,1] ]); # returns [[1,66,'a'],[3,99,'b'],[2,77,'c']]; =cut sub sort_matrix($$) { my $ref_matrix = $_[0]; my @indexMatrix = @{$_[1]}; my @indexes = map {$_->[0]} @indexMatrix; my @operators = map {$_->[1] ? ' cmp ' : ' <=> '} @indexMatrix; my @directions = map {$_->[2]} @indexMatrix; my $body_code = ''; my @body_array; for (my $i = 0; $i <= $#indexes; $i++) { if ($directions[$i]) { push(@body_array, "(\$a->[$i]" . $operators[$i] . "\$b->[$i])"); } else { push(@body_array, "(\$b->[$i]" . $operators[$i] . "\$a->[$i])"); }; }; $body_code = join( ' or ', @body_array); my $array_code = '(map { [' . join(q(, ), map {"\$_->[$_]"} @indexes) . ', $_]} @$ref_matrix)'; my $code = "map {\$_->[-1]} (sort { $body_code} $array_code)"; my @result = eval $code; return [@result]; };