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

I'm trying to sort my array_ref data structure by the first element which is numeric. I know I'm on the right track but I can't quite get there.

How do I fix the sort part of this algorithm?
#!/usr/bin/perl -w use strict; use Data::Dumper; my $array = []; push @$array, [ '1', 'one' ]; push @$array, [ '8', 'eight' ]; push @$array, [ '2', 'two' ]; push @$array, [ '100', 'one hundred' ]; push @$array, [ '4', 'four' ]; push @$array, [ '67', 'sixty seven' ]; my $array2 = sort { $@a->[0] <=> $@b->[0] } @$array; print Dumper \$array2;

Replies are listed 'Best First'.
Re: Sort Array Reference by Numeric First Element
by japhy (Canon) on Jun 11, 2006 at 05:22 UTC
    Change $@a->[0] to $a->[0] or $$a[0] (I suggest and prefer the first form). See perlreftut.

    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
Re: Sort Array Reference by Numeric First Element
by liverpole (Monsignor) on Jun 11, 2006 at 05:23 UTC
    Hi awohld,

    You're very close.  What you want is to remove the '@' signs on the array references, and to put '[ ... ]' around the sort:

    my $array2 = [ sort { $a->[0] <=> $b->[0] } @$array ];

    That should do what you need!


    s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
Re: Sort Array Reference by Numeric First Element
by sh1tn (Priest) on Jun 11, 2006 at 07:56 UTC
    In addition - take a look at sort subroutine. Or (from the command line):
    perldoc -f sort


Re: Sort Array Reference by Numeric First Element
by planetscape (Chancellor) on Jun 11, 2006 at 20:00 UTC