If you had to sort only based upon the keys, you'd write something like this:
Well, you're near. Remember that sort allows you to specify a bare block of code which is actually a sub that's called to establish the relative order of two elements $a and $b. So, you'd change the things a bit like this:for my $k (sort keys %hash) { print "$k $hash{$k}\n"; }
You can include the code in order() directly in sort's block, of course, and use $a and $b instead of $left and $right, but do this only if readability doesn't suffer from this inclusion.my @ordered_keys = sort { order($hash{$a}, $hash{$b}) } keys %hash; for my $k ( @ordered_keys ) { print "$k $hash{$k}\n" } sub order { my ($left, $right) = @_; # Perform comparison between $left and $right. Return # -1 if $left must come *before* $right, 0 if they are # equivalent, +1 if $left must come *after* $right }
The actual implementation of the order() subroutine is left as exercise, but you could extract the last two characters from $left and $right, and use the cmp operator :)
Flavio
perl -ple'$_=reverse' <<<ti.xittelop@oivalf
In reply to Re: Crazy hash sorting issue.
by polettix
in thread Crazy hash sorting issue.
by rementis
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |