There is an old hack from tye at Re: Sorting on Section Numbers that is worth considering. You just pad the numbers to fixed width, and then sort alphabetically. That will sort both numbers and text correctly in most cases. Plus as a bonus it will sort "foo2" before "foo12", which is usually what people want to do.

But if you're building the sort sub dynamically the simplest thing to do is to build an array of sort closures, then combine them into a sort sub. Re: Fun with complex sorting on arbitrary criteria list. can show you how to combine the closures into a single sort subroutine. (Note that there I don't use the ($$) prototype and here I do. That is a good habit because it is very useful to be able to set up the sort routine in one package and call it in the other. It doesn't work on Perl 5.005, but that is not widely used any more.) As for the individual sort subs, they might look something like this (all code is untested):

my $field_index = $position{$field}; if ("text" eq $type{$field}) { if ("asc" eq $order{$field}) { push @sort_sub, sub ($$) { $_[0][0][$field_index] cmp $_[1][0][$field_index]; }; } else { push @sort_sub, sub ($$) { $_[1][0][$field_index] cmp $_[0][0][$field_index]; }; } } else { if ("asc" eq $order{$field}) { push @sort_sub, sub ($$) { $_[0][0][$field_index] <=> $_[1][0][$field_index]; }; } else { push @sort_sub, sub ($$) { $_[1][0][$field_index] <=> $_[0][0][$field_index]; }; } }
And then the actual sort would use a Schwartzian transform like this:
my @sorted_list = map {$_[1]} sort $sort_routine map {[[split $_, "|"], $_]} @list;
Update: I had a trailing comma after sort $sort_routine. Now fixed.

In reply to Re: Build Sort dynamically by tilly
in thread Build Sort dynamically by libvenus

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.