The "my" obviously should be scrapped. demerphq went into that. $a and $b must be package/global variables. That's what sort counts on.

And for a more immediate answer to your question, check out these FAQ entries:

For some more examples, check out perldoc on sort.

The gist of it all is this: the sort block is called to compare two items from the list-to-sort. It will actually be called many times for this one sort statement, in order to establish a complete sorting order for the whole list. The value returned by the block reflects whether the first item ($a) is to be considered bigger or smaller than the second item ($b), depending on the sign of the result. If they are equal, return 0. Your code block should return the same sign as cmp and <=> return, which is not a coincidence, but by design. You might as well use - (minus) for comparing numbers, the results would be quite the same.

print join " ", sort { $a - $b } 1, 3, 2, 5, 4;
This code snippet simply numerically sorts the passed numbers, resulting in a rather boring list.

In reply to Re: question re: hash sorting by bart
in thread question re: hash sorting by Grygonos

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.