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

Hi monks, I'm trying to sort values of hash (that are numeric) but they seem to be evaluating as strings. i.e.
#!/usr/bin/perl use strict; my %hash; $hash{"cat"} = 2; $hash{"dog"} = 1; $hash{"cow"} = 17; my @arr = sort values %hash; print "arr : @arr\n";
which gives...

arr : 1 17 2

How can I make @arr contain a list of numerically sorted values i.e. 1, 2, 17?

Regards Paul

Replies are listed 'Best First'.
Re: sorting question
by holli (Abbot) on Mar 14, 2005 at 19:36 UTC
    my @arr = sort { $a <=> $b } values %hash;

    see perldoc -f sort


    holli, /regexed monk/
      Specifically - "If SUBNAME or BLOCK is omitted, sorts in standard string comparison order."
      --------------
      It's sad that a family can be torn apart by such a such a simple thing as a pack of wild dogs
Re: sorting question
by Limbic~Region (Chancellor) on Mar 14, 2005 at 19:37 UTC
    thekestrel,
    By default, sort uses the cmp operator. Since you want numerical comparison, you need to use the numerical counterpart <=>(spaceship operator).
    print "$_\n" for sort { $a <=> $b } values %hash;

    Cheers - L~R