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

How to sort the numeric elements in array.
@theList = (205, 4, 100, 1, 2, 2000, 6, 93, 2, 65); @theSortedList = sort { lc($a) cmp lc($b) } @theList; print join(',', @theSortedList)."\n";
But I want in the order 1, 2, 2,4, 6,65, 93, 100, 205,2000

How to do this. In perl sorting is based on the first character and takes the ascii values. Is there any way to sort in this order

Replies are listed 'Best First'.
Re: Sort the array
by jwkrahn (Abbot) on Nov 10, 2008 at 07:02 UTC

    First, code tags are  <code> and </code> not  [code] and [/code].

    For a numerical sort you want to use a numerical comparison operator, for example:

    my @theList = ( 205, 4, 100, 1, 2, 2000, 6, 93, 2, 65 ); my @theSortedList = sort { $a <=> $b } @theList; print join( ',', @theSortedList ), "\n";
      Hi,

      your solution works fine. But Can you explain the line a but more ,

      my @theSortedList = sort { $a <=> $b } @theList;

      Since i m new to Perl, i did not understood what its actually doing.
      Thanks,
      Shekar

         <=> is a numeric equality operator.   See perlop for details.    $main::a and  $main::b are special variables that sort uses internally.   So the code block is a call-back subroutine that sort uses to compare the values of the incoming list.