Reputation: 661
Okay, I have a Perl program I'm writing which has a hash of values that I have collected (in a whole separate program altogether) and have fed to this Perl script. This hash is a hash of (string,string).
I want to sort the values 3 ways: First, I want to sort by key. I figured this is easy, you do it exactly the way you would think, using Perl's built in sort function, looping over the keys, and printing/storing/whatevering with each one as they are sorted.
foreach my $name (sort keys %planets) {
printf "%-8s %s\n", $name, $planets{$name};
}
Second, I want to sort by value. Again, this is easy, use the sort function and loop over:
foreach my $name (sort { $planets{$a} <=> $planets{$b} } keys %planets) {
printf "%-8s %s\n", $name, $planets{$name};
}
Third, My question is, how do I sort by value, but for any ties in values between two keys, I sort out first the value which has the greater Asciibetical key. Example:
Red => 50
Yellow => 75
Blue => 75
is sorted to this, since 'Yellow' is greater asciibetically than 'Blue'
Red 50
Blue 75
Yellow 75
Upvotes: 3
Views: 154
Reputation: 98388
On a tie, the comparison operators will return 0, so you can chain several comparisons with ||
:
sort { $planets{$a} <=> $planets{$b} || $a cmp $b }
Upvotes: 10