Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

RE (tilly) 1: Dynamic sort algorithm selection

by tilly (Archbishop)
on Nov 15, 2000 at 05:58 UTC ( [id://41699] : note . print w/replies, xml ) Need Help??


in reply to Dynamic sort algorithm selection

What you want to do is accept a parameter input as the name of an arbitrary function to call? That is a symbolic reference, and is generally a bad idea (particularly in a CGI script - see some of Ovid's posts on that).

Instead I would suggest that you do something like this (untested):

use Carp; # So we can get verbose error messages # Time passes sub ret_str_sorter { my $field = shift; my $direction = shift; if ('ascending' eq $direction) { return sub { $data{$a}{$field} cmp $data{$b}{$field}; }; } elsif ('descending' eq $direction) { return sub { $data{$b}{$field} cmp $data{$a}{$field}; }; } else { confess("Direction '$direction' not understood"); } } # Time passes my $sorter = ret_str_sorter($field, $direction); my @ordered = sort $sorter keys %data;
ObRandomTip: Rather than working with an array of keys into a hash, instead restructure to have an array of anonymous hashes. This will generally lead to a cleaner design and no need to do things like pass the hash definition in through a global.