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

I have a hash that looks like %results{$num} = "something". When I sort it out, it looks like:
1) wrong 10) wrong 11) wrong 12) right 13) wrong 14) wrong 15) wrong 16) wrong 18) wrong 19) wrong 2) wrong
I want the hash keys to be in numerical order 1, 2, 3, 4, 5... How can this be done?

Replies are listed 'Best First'.
Re: sorting hash keys
by salva (Canon) on May 28, 2005 at 19:41 UTC
    read the docs: perldoc -f sort

    anyway...

    @sorted_keys = sort { $a <=> $b } keys %results;
Re: sorting hash keys
by Cody Pendant (Prior) on May 29, 2005 at 06:17 UTC
    All PerlMonks meta-discussion aside, why is this a hash, not an array?


    ($_='kkvvttuu bbooppuuiiffss qqffssmm iibbddllffss')
    =~y~b-v~a-z~s; print
Re: sorting hash keys
by holli (Abbot) on May 28, 2005 at 19:38 UTC
    sort keys { $a <=> $b } %results

    read sort.

    Update:: Correction below.


    holli, /regexed monk/
      Hi

      Thanks for your code but I can't get it to work.

      foreach my $key (sort keys { $a <=> $b } %results) { print MAIL "$key) $results{$key}\n"; }
      Gives me the error Type of arg 1 to keys must be hash (not modulus (%)) at test.pl line 509, near "results) " Bareword "results" not allowed while "strict subs" in use at test.pl line 508. Execution of test.pl aborted due to compilation errors.
        ah, sorry. I'm tired. That should of course be
        foreach my $key (sort { $a <=> $b } keys %results) { print "$key) $results{$key}\n"; }
        my bad.


        holli, /regexed monk/
Re: sorting hash keys
by sh1tn (Priest) on May 29, 2005 at 00:18 UTC
    You may want to try the splendid journey.


Re: sorting hash keys
by thcsoft (Monk) on May 29, 2005 at 01:41 UTC
    honestly, this is the maybe 157th time i'm reading threads like this one. does anyone of you anonymous monks ever have the idea of giving the searchbar a try? it's absolutely annoying and imho a misuse of this forum, what you do. :(

    language is a virus from outer space.

      And you expect all future anonymonks to stumble upon this note of yours, slap their foreheads, and say, "Of course! I'll get right on it!" ??

      In my opinion, the two choices are: allow anonymonks, or get rid of significant portions of duplication. And I'm not even too sure that you'll get rid of enough to satisfy your frustration.

      I understand your frustration, but you need to relax a bit, realise what is under your (or anyone's) control, what isn't, and save your energy and angst for that which you can do something about, and that which is actually important. ;-)