in reply to Re^3: How would I sort a two-dimensional array by multiple columns?
in thread How would I sort a two-dimensional array by multiple columns?

Sorry NetWallah, I was refering to Funk's code. I saw your previous comment, however your code appears to be sorting all depths and I need "sortRoutine(@array, 2, 1, 4, 5) for example.

I have an existing piece of code that has an array of arrays that needs to be sorted like this and Funk's code was sorting an array of refs.


  • Comment on Re^4: How would I sort a two-dimensional array by multiple columns?

Replies are listed 'Best First'.
Re^5: How would I sort a two-dimensional array by multiple columns?
by FunkyMonk (Bishop) on Mar 16, 2008 at 14:29 UTC
    The changes needed to make the sub sort arrays are minor:
    use Test::More qw/no_plan/; my @unsorted = ( [ qw/1 3 5 6 2/ ], [ qw/3 4 5 6 7/ ], [ qw/1 2 3 4 5/ ], [ qw/5 6 7 8 8/ ], [ qw/1 2 3 4 5/ ], [ qw/2 2 2 2 2/ ], [ qw/1 1 2 4 5/ ], [ qw/2 3 4 5 6/ ], ); my @expected = ( [ qw/1 1 2 4 5/ ], [ qw/1 2 3 4 5/ ], [ qw/1 2 3 4 5/ ], [ qw/1 3 5 6 2/ ], [ qw/2 2 2 2 2/ ], [ qw/2 3 4 5 6/ ], [ qw/3 4 5 6 7/ ], [ qw/5 6 7 8 8/ ], ); my @sorted = sortSub(\@unsorted, 0, 1, 3); # sort by first, second & f +ourth columns is_deeply \@sorted, \@expected; sub sortSub { my @array = @{ +shift }; return sort { for my $ix ( @_ ) { my $cmp = $a->[$ix] <=> $b->[$ix]; return $cmp if $cmp; } return 0; } @array; }

    I think you're calling the first column 1, whereas Perl considers the first column to be 0. In that case you'll need adjust the column numbers accordingly.

      Thanks funky. I understand the index array index starting at 0 :). I read the "the Llama book", however, the arrays inside of arrays is a somewhat new concept.

      Thanks a trillion for the help!

      After all this is over, all that will really have mattered is how we treated each other.