Let's say you have some hash:

my %h = ( Foo => 73, Bar => 66, Rat => -1 );

If you say sort keys %h you know will get the order Bar, Foo, Rat, which means when you look through the hash in that order you will find 66, 73, -1. You could also say sort { $a cmp $b } keys %h, but that would be a little redundant.

In essence, the sort routine is going to compare Foo with Bar, Bar with Rat and Rat with Foo to decide on the order.

If, however, instead of saying {$a cmp $b} we were to say {$h{$a} <=> $h{$b}}, we would be sorting on the value that Foo et al., point to. So we would be comparing 66 with 73, 66 with -1 and 73 with -1. We have to use the spaceship operator <=> because we are performing numerical comparisons.

If we were to foreach over the hash with the results of this sort, we would see Rat, Bar, Foo.

I hope that helps you understand how it works. It is a very useful trick to have around.

--
g r i n d e r

In reply to Re: sort keys question by grinder
in thread sort keys question by treebeard

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.