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

Hi monks

I want to sort the numbers in the ascending order. but the files consist of ndash in it.

INPUT: @a=(21,14,15–21,15,16) OUTPUT: @a=(14,15,15–21,16,21)

But when I sort this input array i get the output as @a=(14,15–21,15,16,21).

I want the output as mentioned inside the code tag. So how should be this done.

Many thanks in advance.

jdporter - changed title from "sorting"

Replies are listed 'Best First'.
Re: Problem sorting strings numerically
by Zaxo (Archbishop) on May 11, 2004 at 05:38 UTC

    Here, @a = sort {$a <=> $b or length($a) <=> length($b)} @a; 15 and '15&ndash;21' both become 15 in numeric context. When numeric values are equal, length of string is taken as a tiebreaker.

    After Compline,
    Zaxo

Re: Problem sorting strings numerically
by matija (Priest) on May 11, 2004 at 05:41 UTC
    The problem is that by default sort uses strict numeric comparisons. To those comparisons, 15 and 15&ndash;21 look the same. You should write your own comparison function, one that will check for the ndash, and do the right thing.

    Of course, you'll need to decide what to do when you get two ndash strings with identical lower bounds and different upperbounds - or decide that can not happen, and then document that in the comments.