I need to be able to sort a hash by values, but i cannot inline the sort function, because it will not be specified until runtime. So i cant use the usual:
foreach my $key ( sort { $hash{$a} cmp $hash{$b} } keys %hash ) { # do something useful }
sort of thing.

I will need to use a named sort function, specified at runtime, but something like this will not work:

foreach my $key ( sort my_sorter keys %hash ) { # do something useful } ... ... sub my_sorter { return $hash{$a} cmp $hash{$b}; }
Because %hash is not necessarily scoped in my_sorter()

In my situation, it will be nearly impossible to have the hash being sorted in the proper scope directly.

What i realy want to do is pass anonymous sort subroutines into the function that needs to sort the hash, but i just dont see how to make this work properly. The hash itself will always be out of scope.

Note that this is a simplification of the real problem, the sorting by values problem is only part of the situation, but its the only part thats giving me trouble.

So i guess the real issue is: How do i sort by values without an inlined sort?

Thanks much - beating my head


In reply to Sort by value - new twist by shemp

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.