Here’s an alpha sort of the values of the associative array named “myarray”:
1 2 3 |
foreach my $key (sort {$myarray{$a} cmp $myarray{$b}} keys %myarray) { print "$key : " . $myarray{$key} . "\n"; }; |
And here’s the same sort numerically:
1 2 3 |
foreach my $key (sort {$myarray{$a} <=> $myarray{$b}} keys %myarray) { print "$key : " . $myarray{$key} . "\n"; }; |
And if you want numeric descending:
1 2 3 |
foreach my $key (sort {$myarray{$b} <=> $myarray{$a}} keys %myarray) { print "$key : " . $myarray{$key} . "\n"; }; |
Of course don’t forget how to sort keys:
1 2 3 |
foreach my $key (sort keys %myarray) { print "$key : " . $myarray{$key} . "\n"; }; |
And a numerical sort of keys:
1 2 3 |
foreach my $key (sort {$a<=>$b} keys %myarray) { print "$key : " . $myarray{$key} . "\n"; }; |