Basic sorting of Perl hash by key, by value, but also by AND key
Okay, I have a Perl program that I am writing that has a hash of values ββthat I have collected (generally, separately) and downloaded this Perl script. This hash is a hash (string, string).
I want to sort values ββin 3 ways: firstly, I want to sort by key. I figured it was easy, you do it exactly as you think using Perl's built in sort function, iterating over the keys and printing / saving / regardless of each one when sorting them.
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 a sort function and a loop:
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 relationships between values ββbetween two keys, I first sort the value that has the higher 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
+3
source to share