Your node title says you wish to sort by key. Your question says you would like to sort by value. And your script is sorting by key. 2:1, I'm going to assume you wish to sort by key. In that case, your problem is that you're doing an ascii-betical sort instead of a numeric sort. Try this:

foreach $number ( sort { $a <=> $b } keys %name ) { print "\t$number\t\t$name{$number}\n"; }

You may have another problem too. Hash keys are unique. That means you can only have one of each 'number'. You're ok if you keep that in mind. But if the numbers represent, for example, scores, it would be possible that different names are associated with the same numbers, in which case you lose some filenames when converting to a hash. This may not be an issue for you. In your example file it looks (from the three lines you showed) like there are no duplicate numbers. Just make sure that's really the case.

Also, don't forget to chomp before splitting, unless you want your filenames to come with newlines attached to them.


Dave


In reply to Re: sorting a hash by key by davido
in thread sorting a hash by key by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.