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

I'm a litle bit puzzeled about sorting. The following code:
print join (', ' , sort {$a <=> $b || $a cmp $b} (2, 0, 1, 99, 'aaa', 'AAA', undef, 'ZZZ', 'zzz')) , "\n";
produces
__OUTPUT__ , 0, AAA, ZZZ, aaa, zzz, 1, 2, 99
• Why is undef the first item?
• Why is 0 not within the other numbers?
Thanks for any hints!

pelagic

Replies are listed 'Best First'.
Re: Puzzeled about Sorting
by Zaxo (Archbishop) on Jun 10, 2004 at 11:23 UTC

    In numeric context given by the first comparison, undef, 0, and all the alphabetic strings evaluate to numeric zero. Being equal in numeric context, the comparison evaluates to 0 and the dictionary sort order kicks in. In string context undef is the empty string, which sorts first, then '0', then the alphabetic quantities in lexicographic order.

    Here's an example worth working out in your head before you try it: $ perl -e'print join( ", ", sort {$a<=>$b || $a cmp $b} qw/7 000 07 00 007 0/, "0 but true"), $/'

    After Compline,
    Zaxo

Re: Puzzeled about Sorting
by dave_the_m (Monsignor) on Jun 10, 2004 at 11:31 UTC
    First you do a numeric sort. In this case, undef and the strings take on the value zero in a numeric context. Thus, 0, undef, 'aaa', 'AAA', 'ZZZ' and 'zzz' all compare equally and come before the >0 numbers. Then for all the ones above that are numerically equivalent to 0, you do a string comparison; now in string cxontext, undef is treated as the empty string "" and 0 is treated as the one character string "0". Thus they get sorted as undef, 0, AAA, ZZZ, aaa, zzz.
    Running with warnings enabled might be illuminating at this point.

    Dave.

Re: Puzzeled about Sorting ('natural')
by tye (Sage) on Jun 10, 2004 at 16:48 UTC

    There are some fairly simple ways to get the numbers sorted together, found by searching for natural sort.

    - tye        

Re: Puzzeled about Sorting
by pelagic (Priest) on Jun 10, 2004 at 11:59 UTC
    Thanks a lot guys for that lesson!

    pelagic
Re: Puzzeled about Sorting
by Anonymous Monk on Jun 12, 2004 at 04:55 UTC

    Ok, think about what your sort routine does:

    sort {$a <=> $b || $a cmp $b}

    It means that if $a and $b are equal numerically, then it will do a string comparison on them.