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

Hi,

What would be the most efficient (i.e. least time consuming and least lines of code) way to sort through a two dimensional array by one column containing numeric values?

  • Comment on sorting a two dimensional array by one column

Replies are listed 'Best First'.
Re: sorting a two dimensional array by one column
by Zaxo (Archbishop) on Jul 14, 2003 at 08:18 UTC
    my @sorted = sort { $a->[$the_col] <=> $b->[$the_col] } @two_dim;

    Have a look at perllol.

    After Compline,
    Zaxo

Re: sorting a two dimensional array by one column
by antirice (Priest) on Jul 14, 2003 at 08:18 UTC
    Use the sort command and the numerical comparison operator (<=>).
    my @sorted = sort { $a->[$col] <=> $b->[$col] } @origarray;

    antirice    
    The first rule of Perl club is - use Perl
    The
    ith rule of Perl club is - follow rule i - 1 for i > 1

Re: sorting a two dimensional array by one column
by bigj (Monk) on Jul 14, 2003 at 15:32 UTC

    In addition to the others, there is a shorter way to sort for the first column of a two dimensional array:

    my @sorted = sort {"@$a" <=> "@$b"} @two_dim;
    

    But please don't use it in production code :-)

    Greetings,
    Janek