Fellow monks,
I'm in the midst of a rewrite of a piece of code that is completely unflexible. One of the things that I'm attempting to do in adding flexibility to the code, is allow sorting based on a coderef.

So, I have a many dimensional hash that I'm using to setup parameters for how something should work. I would like to have one of the (optional) keys along the way be a 'sort' key with a coderef as the value.

This is relatively easy to do, the problem comes in when I am attempting to call a sort routine that accepts parameters..
$parameter_hash->{$this}{$value}{sort_by} = \&custom_sort; ... later, in some other subroutine ... my $sort_routine = $parameter_hash->{$this}{$value}{sort_by} || #other + standard sorts here; foreach (sort $sort_routine keys %{ $parameter_hash->{$this}{$value}{v +alue_list} }) { #do stuff }
The above works fine, sorts based on $a/$b comparison/whatever. The problem is, when I want to sort (for example) a hash based on value. The sort routine needs the hash..
foreach (sort $sort_routine->(\%href) keys %{ $somehashref }) { #do stff }
This fails with a syntax error, as does:
sort &{ $sort_routine }(\%href); sort &{ $sort_routine(\%href) };
and other variations of the sort.

I guess, because this is a new script, I could rethink how I'm building the list(s) that will need sorting, but my preference would be to somehow get the above going.

Thanks in advance for any advice.

In reply to Sorting using coderef's, and passing parameters by the_slycer

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.