First, the following allow you to switch the procedure being called:
$sorter = \&my_sorter; foreach my $key (sort { &$sorter } keys %hash ) { # do something useful }
Update:
Because %hash is not necessarily scoped in my_sorter
Option 1
$sorter = \&my_sorter; foreach my $key (sort { &$sorter(\%hash) } keys %hash ) { # do something useful } sub my_sorter { my ($hashref) = @_; return $hashref->{$a} cmp $hashref->{$b}; }
Option 2
$sorter = \&my_sorter; foreach my $key ( map { $_->[0] } sort { &$sorter } map { [ $_, $hash{$_} ] } keys %hash ) { # do something useful } sub my_sorter { return $a->[1] cmp $b->[1]; }
Option 3
Use local %hash = %the_hash_to_process; before the foreach, and our %hash inside my_sorter.
There are more ways.
In reply to Re: Sort by value - new twist
by ikegami
in thread Sort by value - new twist
by shemp
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |