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

Hello, I hate to waste your time with such a simple question, but I need to sort an array that consists of numeric elements.

The sort routine does the job, but only looks at the first digit of each element. This works for single numbers, but my array contains 2 or more digit numbers, This is the code I'm working with;

use strict; @event_queue = ("18", "503", "103", "501", "53"); @event_queue = sort(@event_queue); foreach $_ (@event_queue){ print "$_\n"; }

This produces:

103 18 502 503 53
The sort should look like this:
18 53 103 502 503
Any suggestions?

Replies are listed 'Best First'.
Re: Array Sort
by davis (Vicar) on Sep 10, 2002 at 11:42 UTC
    That's because sort does a lexical sort by default, and you want a numerical sort. Compare the "magic" sort variables $a and $b using the spaceship operator.
    perldoc -f sort Reveals the following:
    # sort numerically ascending @articles = sort {$a <=> $b} @files; # sort numerically descending @articles = sort {$b <=> $a} @files;
    Cheers
    Update:Ahah!. Knew it was around here somewhere! Under Categorized Questions and Answers, in the sorting subsection (Although it might benefit from being in the array section as well), you'll find How do I sort a list of numbers?

    davis
    Is this going out live?
    No, Homer, very few cartoons are broadcast live - it's a terrible strain on the animator's wrist
Re: Array Sort
by JaWi (Hermit) on Sep 10, 2002 at 11:44 UTC
    That's because it handles each element of your array as string. You probably want this:
    ... @event_queue = sort { $a <=> $b } @event_queue; ...

    BTW: you don't need to explitly assign the $_ operator in the foreach loop. It is done automatically...

    Greets,

    -- JaWi

    "A chicken is an egg's way of producing more eggs."

      That worked!

      I always learn something when I post, like the absence of $_ in a foreach loop
      Thanks Again!

Re: Array Sort
by Anonymous Monk on Sep 10, 2002 at 16:45 UTC
    Sorting positive integers using the Guttman Rosler Transform:
    @event_queue = ("18", "503", "103", "501", "53"); @event_queue = map{(split)[1]} sort map{(length length).(length)." $_"} @event_queue;