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

How would I make this work if I am passing in @unsorted rather than $unsorted?

After all this is over, all that will really have mattered is how we treated each other.
  • Comment on Re^2: How would I sort a two-dimensional array by multiple columns?

Replies are listed 'Best First'.
Re^3: How would I sort a two-dimensional array by multiple columns?
by NetWallah (Canon) on Mar 16, 2008 at 05:09 UTC
    I had already indicated that in the comment of my previous node. Here it is again:
    my @sorted = sort NetWallahSort @unsorted;
    Note : I have updated "sub NetWallahSort" in the posted code, to include ikegami's suggestion, returning "0" instead of "1" when sort elements are equal. Please use a current copy of that code.

         "As you get older three things happen. The first is your memory goes, and I can't remember the other two... " - Sir Norman Wisdom

      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.


        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.