Hardly any eval STRING necessary. You can do entirely without, but it's not practical.
use Carp; use vars qw(%data); my %comparison; sub init_comparison_for { local $_ = shift; my $op = /^string/ ? 'cmp' : /^num/ ? '<=> : croak "unknown comparison type $_"; @comparison{@_} = map { eval "sub { \$data{\$a}{$_} $op \$data{\$b}{$_} }" } @_; @comparison{map "r-$_", @_} = map { eval "sub { \$data{\$b}{$_} $op \$data{\$a}{$_} }" } @_; } sub sortedkeys (\%@) { my $hash; unless( ($hash = shift) and ('HASH' eq ref $hash) ) { croak "not a hashref: $hash"; } local *data = shift; my @funcs = @comparison{@_}; if(my @unknown = grep !defined $func[$_], 0 .. $#_) { croak "unknown field name(s): @unknown"; } sort { my $r = 0; ($r ||= &$_) && last for @funcs; $r } keys %data; }
Use as in
init_comparison_for string => qw(fname lname email address position); init_comparison_for numeric => qw(id salary zip); print $employee{$_}->{fname}, " ", $employee{$_}->{lname} for sortedkeys %employee, qw(r-salary id);
This should be improved by taking and returning a hashref in the initialization so there can be multiple different comparison function tables. It might be worthing turning this into an object. You can get even fancier with a tied interface to override the keys behaviour.. the possibilities are endless. (I'm surprised noone has written a module for that yet.)

Makeshifts last the longest.


In reply to Re: Generate Dynamic Sort Expressions by Aristotle
in thread Generate Dynamic Sort Expressions by lofichurch

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.