Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to sort a two-dimensional array, alphabetically, by just the first column. I've come up with the following, but it doesn't work. It seems to just throw the first row at the end.

I fear it's obvious, but I don't really know what I am doing.

@unsorted_array = ([f, g, h, i, j], [a, b, c, d, e], [k, l, o, n, r], [j, a, o, n, e], [f, p, r, t, u]); @big_table_array = sort {uc($a) cmp uc($b)}@unsorted_array; $output_array_tracker = 0; while ($output_array_tracker < ($#unsorted_array + 1)){ print "$big_table_array[$output_array_tracker][0], $big_table_array[$output_array_tracker][1], $big_table_array[$output_array_tracker][2], $big_table_array[$output_array_tracker][3], $big_table_array[$output_array_tracker][4], $big_table_array[$output_array_tracker][5] \n"; $output_array_tracker = $output_array_tracker + 1; }

Replies are listed 'Best First'.
Re: Sort a two-dimensional array?
by gjb (Vicar) on Dec 20, 2002 at 22:14 UTC

    sort {uc($a->[0]) cmp uc($b->[0])} @unsorted_array should work.

    Hope this helps, -gjb-

      It does, thanks.
Re: Sort a two-dimensional array?
by Paladin (Vicar) on Dec 20, 2002 at 22:20 UTC
    In your code, $a and $b are elements of @unsorted_array which are arrayrefs. You need to dereference them to get the actual element you want to sort on.
    @unsorted_array = ([f, g, h, i, j], [a, b, c, d, e], [k, l, o, n, r], [j, a, o, n, e], [f, p, r, t, u]); @big_table_array = sort {uc($a->[0]) cmp uc($b->[0])} @unsorted_array;
Re: Sort a two-dimensional array?
by dempa (Friar) on Dec 20, 2002 at 22:14 UTC

    In your sort, $a and $b are references to arrays. To access the first row (row 0) you need to dereference the arrays first. Change $a and $b to ${$a}[0] and ${$b}[0] in your sort routine.

    -- 
    dempa

Re: Sort a two-dimensional array?
by seattlejohn (Deacon) on Dec 21, 2002 at 04:12 UTC
    Others have accurately explained how to get the sort to work the way you want, but I thought this would also be a good opportunity to tell you about the eminently useful Data::Dumper module, which will let you eliminate that unsightly loop at the end of your code.
    use Data::Dumper; # ... your sort code here ... print Dumper \@big_table_array;

    Data::Dumper is handy to have in your toolbox when it's time for this kind of inspection.

            $perlmonks{seattlejohn} = 'John Clyman';