Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Generate Dynamic Sort Expressions

by Aristotle (Chancellor)
on Nov 28, 2002 at 14:49 UTC ( [id://216310]=note: print w/replies, xml ) Need Help??


in reply to Generate Dynamic Sort Expressions

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://216310]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (7)
As of 2024-04-23 10:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found