in reply to A generic sorting problem

I think you should use the cmp and <=> operators in the sort subroutine, like this :
@a = qw( words only contains ); @b = qw( 8 3 7 1 ); print join( " ", sort { $a <=> $b || $a cmp $b } @a ), "\n"; # contains only words print join( " ", sort { $a <=> $b || $a cmp $b } @b ), "\n"; # 1 3 7 8
This way you can even sort numbers AND letters :
@a = qw( 2 two 1 one ); print join( " ", sort { $a cmp $b || $a <=> $b } @a ), "\n"; # 1 2 one two

Replies are listed 'Best First'.
Re: Re: A generic sorting problem
by demerphq (Chancellor) on Jul 19, 2002 at 10:25 UTC
    Your first two examples would raise warnings galore when handling non numeric values, and the second example is simply an alphabetic sort, equivelent to sort @a

    use warnings; use strict; my @a = qw( 2 two 1 11 12 one 3abcd 6foo ); print join( " ", sort { $a <=> $b || $a cmp $b } @a ), "\n"; __END__ Argument "two" isn't numeric in numeric comparison (<=>) at c:\temp\so +rt.pl line 4. Argument "one" isn't numeric in numeric comparison (<=>) at c:\temp\so +rt.pl line 4. Argument "3abcd" isn't numeric in numeric comparison (<=>) at c:\temp\ +sort.pl line 4. Argument "6foo" isn't numeric in numeric comparison (<=>) at c:\temp\s +ort.pl line 4. one two 1 2 3abcd 6foo 11 12
    and
    #... print join( " ", sort { $a cmp $b || $a <=> $b } @a ), "\n"; __END__ 1 11 12 2 3abcd 6foo one two

    Yves / DeMerphq
    ---
    Writing a good benchmark isnt as easy as it might look.

      Oops :( you are absolutely right !

      But is there a way to do this without getting the warnings messages ? by localizing $^W I guess ? or simply by not using this kind of construction :)))