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

I know you can sort an array using "sort(@array);" but this doesn't seem to work with an array of arrays though.
How can I sort my AoA using the first element of each array as the sort criteria?
@array=( ["def","456","$%^"], ["abc","123","!@#"], ["ghi","789","&*("] ); #code to sort the aoa here for $i ( 0 .. $#array ) { print "$array[$i][0]\n"; }
Should output:

abc
def
ghi

--
Ah, thanks! So simple yet I couldn't figure it out.

Replies are listed 'Best First'.
Re: Sorting an AoA?
by FunkyMonk (Bishop) on Feb 12, 2008 at 18:54 UTC
    @array = sort { $a->[0] cmp $b->[0] } @array; # ascending #@array = sort { $b->[0] cmp $a->[0] } @array; # descending

    Update:

    for my $i ( 0 .. $#array ) isn't a very Perlish way of iterating over an array.

    Both

    for my $elem ( @array ) { print "$elem->[0]\n"; }

    and

    print "$_->[0]\n" for @array;

    are considered more idiomatic.

Re: Sorting an AoA?
by kyle (Abbot) on Feb 12, 2008 at 18:57 UTC
Re: Sorting an AoA?
by sh1tn (Priest) on Feb 13, 2008 at 00:17 UTC