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

I have a simple problem that i need help with! my prob is im sorting two fields one of which is string the other an integer.

im sorting by the number first (decrement) then alphabetically with the string! my prob. is with the number being treated as a string so that the result becomes (9,8,7,6,5,4,3,2,1,10,11,12...) instead of (... 12,11,10,9,8..), how do i fix this. need help please.

@paths = sort {$MyInteger{$b} . "$MyString{$a}" cmp $MyInteger{$a} . "$MyString{$b}" } keys %MyKeys;

Replies are listed 'Best First'.
Re: sorting with number then string
by pfaut (Priest) on Feb 18, 2003 at 15:08 UTC

    Use separate comparisons. That way you can control numeric vs. string comparisons.

    @paths = sort { $MyInteger{$b} <=> $MyInteger{$a} || $MyString{$a} cmp $MyString{$b} } keys %MyKeys;
    --- print map { my ($m)=1<<hex($_)&11?' ':''; $m.=substr('AHJPacehklnorstu',hex($_),1) } split //,'2fde0abe76c36c914586c';
Re: sorting with number then string
by tommyw (Hermit) on Feb 18, 2003 at 15:09 UTC

    Reading the documentation:
    Binary "<=>" returns -1, 0, or 1 depending on whether the left argument is numerically less than, equal to, or greater than the right argument.
    ...
    Binary "cmp" returns -1, 0, or 1 depending on whether the left argument is stringwise less than, equal to, or greater than the right argument.

    So that's why your numbers are being treated as strings: you've used the string comparison.

    Next problem: "how to sort on multiple keys" is left as an exercise for the reader.

    --
    Tommy
    Too stupid to live.
    Too stubborn to die.