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

Re: Choosing the sort routine on the fly

by hawtin (Prior)
on Sep 08, 2006 at 08:05 UTC ( [id://571895]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2024-03-28 20:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found