http://www.perlmonks.org?node_id=11111573

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

Hi all, I am trying to sort an array of arrays, but i am stuck. I have red some sources on the internet, but it is not helping me enough. I hope someone can tell me why i am failing. I am trying to sort this array on the second element. Here is the code:

@ar = ([1,12],[8,3],[4,57],[22,5]); @sort = sort{$a[1]<=>$b[1]}@ar; foreach (@sort){ print "@$_\n";}

The desired output is: 8,3 22,5 1,12 4,57. But all i'm getting is the same sorting as i started with. Tx in advance.

Replies are listed 'Best First'.
Re: sorting array of arrays
by hippo (Bishop) on Jan 18, 2020 at 17:27 UTC

    Your sorting code treats each element of @ar as an array when it is instead an array ref. Using warnings would have alerted you to that.

    @ar = ([1,12],[8,3],[4,57],[22,5]); @sort = sort{$a->[1]<=>$b->[1]}@ar; foreach (@sort){ print "@$_\n"; }

      Tx.

Re: sorting array of arrays
by AnomalousMonk (Archbishop) on Jan 18, 2020 at 20:13 UTC

    Further to hippo's post:   Note that going a step further and enabling strictures with  usestrict; would have prevented the code from compiling in the first place:

    c:\@Work\Perl\monks>perl -le "use strict; use warnings; ;; my @ar = ([1,12],[8,3],[4,57],[22,5]); my @sort = sort{$a[1]<=>$b[1]}@ar; foreach (@sort){ print \"@$_\n\";} " Global symbol "@a" requires explicit package name at -e line 1. Global symbol "@b" requires explicit package name at -e line 1. Execution of -e aborted due to compilation errors.
    (I have to admit the  Global symbol "@a" requires explicit package name ... etc messages are slightly more obscure, but they explicitly point you to the offending variable.)

    See also How do I sort an array by (anything)? in the Data: Arrays section of perlfaq4.


    Give a man a fish:  <%-{-{-{-<

      you miss "->"
      use strict; use warnings; ;; my @ar = ([1,12],[8,3],[4,57],[22,5]); my @sort = sort{$a->[1]<=>$b->[1]}@ar; foreach (@sort){ print "@$_\n";}

      PS D:\perl\perlmonks> perl .\sort.pl
      8 3
      22 5
      1 12
      4 57

        But the point of my post and part of the point of hippo's before it is that if warnings and/or strict had been used, Perl would not have, so to speak, "missed" the  -> operator.

        Update: Oh... Or did you mean to respond to the OP?


        Give a man a fish:  <%-{-{-{-<