This works:
my %score = ( a => 1, b => 2);
@keys = sort {$score{$a} <=> $score{$b}} keys %score;
But how can I put the code inside {..} to a dedicated sub routine?
sub by_num {
$score{$a} <=> $score{$b}
}
@keys = sort by_num keys %score;
?
The main problem here is having a subroutine that has access to the hash. You either have to create one function per hash you want to sort:
Or create a higher-order function that creates the functions for you:
But all of that is, generally, wasted effort for both the programmer and the computer. The block syntax is faster and easier to use in almost all cases. The only exceptions would be complicated sorts or highly repetitive code.