in reply to Sort by value - new twist
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Sort by value - new twist
by shemp (Deacon) on Sep 01, 2004 at 19:29 UTC | |
by Limbic~Region (Chancellor) on Sep 01, 2004 at 22:07 UTC | |
|
Re^2: Sort by value - new twist
by ihb (Deacon) on Sep 02, 2004 at 01:44 UTC |