Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Re: Comparing spaceships (cmp and <=> as options)

by choroba (Archbishop)
on May 20, 2013 at 15:54 UTC ( #1034359=note: print w/replies, xml ) Need Help??

in reply to Comparing spaceships (cmp and <=> as options)

sub returns a code reference on its own, no need to add a backslash. You have to add parameters to the subs, though. The canonical ones for sort are $a and $b. Localize them to the value to be sorted on so that the code still returns the full record.
#!/usr/bin/perl use warnings; use strict; my $sort = 'hours'; # really comes from a switch my %map = ( # sorting map hours => [0, sub {$a <=> $b}], code => [1, sub {$a cmp $b}], name => [2, sub {$a cmp $b}], ); # example data my @records = ( [10, 'xyz232', 'secret project'], [ 5, 'foo123', 'world domination'], [ 7, 'bar666', 'have a beer'], ); for ( sort { local ($a, $b) = map $_->[$map{$sort}->[0]], $a, $b; $map{$sort}[1]->(); } @records ) { print "@$_\n"; }
لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2019-12-06 20:57 GMT
Find Nodes?
    Voting Booth?
    Strict and warnings: which comes first?

    Results (159 votes). Check out past polls.