in reply to Sort by value - new twist
Enter functional programming techniques.
sub by_hashval_func { my ( $hashref ) = @_; return sub { $hashref->{ $a } cmp $hashref->{ $b } }; } foreach my $key ( sort by_hashval_func( \%hash ) keys %hash ) { # do something useful }
Update: I just remembered that $a and $b are package globals, ie the above will not work if by_hashval_func is in a different package than the sort call ultimately using the closure. To cater to that case, the prototyped sort block form is necessary:
sub by_hashval_func { my ( $hashref ) = @_; return sub($$) { $hashref->{ $_[0] } cmp $hashref->{ $_[1] } }; }
Makeshifts last the longest.
|
|---|