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

Hi Monks, I am trying to sort an array using the Schwartzian transform on the first element of num1_num2
use strict; my @unsorted = ( '864278_864377', '864518_864703', '851171_851270', '855398_855579', '856258_856357', '861015_861139', '866387_866549', '791806_792296', '1088806_1082296', ); my @sorted = map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [ $_, ( split(/\_/, $_) )[0] ] } @unsorted; print join ("\n",@sorted);
I am expecting the sorted array to be in this order:
791806_792296 851171_851270 855398_855579 856258_856357 861015_861139 864278_864377 864518_864703 1088806_1082296
Instead I am getting this:
1088806_1082296 791806_792296 851171_851270 855398_855579 856258_856357 861015_861139 864278_864377 864518_864703 866387_866549
I just can't figure out how to fix this! Thanks much for your input!
UPDATE: I fixed it by using  <=> numeric sort!

Replies are listed 'Best First'.
Re: Sort an array using the Schwartzian transform
by Anonyrnous Monk (Hermit) on Jan 21, 2011 at 17:39 UTC
    sort { $a->[1] cmp $b->[1] } ^^^

    You want <=> for numeric comparison, not cmp.

Re: Sort an array using the Schwartzian transform
by toolic (Bishop) on Jan 21, 2011 at 19:49 UTC
    Unrelated to the problem which you already fixed... here are some tips (which you might already know)

    You can save yourself some typing by eliminating those quotes and commas. Use qw as a list constructor.

    my @unsorted = qw( 864278_864377 864518_864703 851171_851270 855398_855579 856258_856357 861015_861139 866387_866549 791806_792296 1088806_1082296 );

    Also, the Core Data::Dumper module is handy for printing arbitrary data structures:

    use Data::Dumper; print Dumper(\@sorted);
Re: Sort an array using the Schwartzian transform
by JavaFan (Canon) on Jan 21, 2011 at 20:01 UTC
    There's no need for any transform here.
    my @sorted = sort {do {no warnings 'numeric'; $a <=> $b}} @unsorted;
    will do. (Or some other variation to turn the warning off).

    I wish people would stop bending their code backwards just to avoid a warning. Don't be afraid to turn warnings off in such cases.

      Oops, I though that your code was wrong because
      DB<1> x sort { $a <=> $b } (1_0, 1_00, 2_0 ) 0 10 1 20 2 100
      but actually...
      DB<2> x sort { $a <=> $b } qw(1_0 1_00 2_0) 0 '1_0' 1 '1_00' 2 '2_0'
Re: Sort an array using the Schwartzian transform
by ikegami (Patriarch) on Jan 21, 2011 at 18:27 UTC

    Why are you making your code messier by using ST?

    You must not have needed the optimisation if you didn't notice that you made your code slower at the same time as you made it messier! (Well, probably. ST is actually somewhat expensive, but it's possible that switching to it sped things up by a very tiny amount.)

Re: Sort an array using the Schwartzian transform
by umasuresh (Hermit) on Jan 21, 2011 at 20:59 UTC
    Thank you all for your valuable suggestions!