in reply to Choosing the sort routine on the fly
I had a similar problem, I wanted to create a sort function that kept track of which attributes to use, so I used a closure:
sub sort_fun { # Get a has ref and and sort spec my($hash_ref,$sort) = @_; my @sort_columns = split(/[\|\,\+]/,$sort); # Do some stuff... # Create a closure function return sub { # Test stuff... foreach my $col (@sort_columns) { # lexically() is like an extended version of cmp my $ret = lexically($hash_ref->{$a}->{$col}, $hash_ref->{$b}->{$col}); return $ret if($ret != 0); } return 0; } } my $sort_fun = sort_fun(\%tracks,"year|name"); foreach my $id (sort $sort_fun keys(%tracks)) { # Do something for every $id }
The hardest part was creating a thing that sort would accept as a function.
|
|---|