Hi Monks.

I imagine that there is a good, accepted way to do this, but it seems that I can't find the right words to bash in to google.

Copying from the O'REILLY "Programming Perl" book (and simplifying a bit), I have, for example :

sub prospects { $b->{SALARY} <=> $a->{SALARY} || $b->{HEIGHT} <=> $a->{HEIGHT} || $b->{AGE} <=> $a->{AGE} } @sorted = sort prospects @recs

Now, I inderstand that, but I wand to be able to sort on different fields, and potentially a different number of fields. I'd like to be able to pass the keys to be sorted on to a sub somehow. I could do it with, e.g., maximum 10 fields allowed for, but I would like it to work with any number of fields. I can't work out how to do it without an eval, which I'd like to avoid.

Ideally I would like to be able to use different sort operators / subs with each key, perhaps by passing my function an array something like :

[ { KeyName => 'SALARY', SortType => '<=>' }, { KeyName => 'FIRST_NAME', SortType => 'cmp' } ]

So I basically want to make a function that is used like :

@sorted_hash_ref = flexible_sort( \@unsorted_hash_refs, \@sort_config );

Apologies for poor terminology etc. Thanks in advance!


In reply to sort by variable, configurable fields by Tharg

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.