« Yum : Howto download source packagesEncode/decode SMTP AUTH username/passwords »

Perl - Sort associative array by value

03/21/09

Permalink 03:59:57 pm, by admin Email , 71 words   English (US)
Categories: Misc

Perl - Sort associative array by value

Here's an alpha sort of the values of the associative array named "myarray":

foreach my $key (sort {$myarray{$a} cmp $myarray{$b}} keys %myarray) {
print "$key : " . $myarray{$key} . "\n";
};

And here's the same sort numerically:

foreach my $key (sort {$myarray{$a} <=> $myarray{$b}} keys %myarray) {
print "$key : " . $myarray{$key} . "\n";
};

And if you want numeric descending:

foreach my $key (sort {$myarray{$b} <=> $myarray{$a}} keys %myarray) {
print "$key : " . $myarray{$key} . "\n";
};

No feedback yet

Leave a comment


Your email address will not be revealed on this site.

Your URL will be displayed.
PoorExcellent
(Line breaks become <br />)
(Name, email & website)
(Allow users to contact you through a message form (your email will not be revealed.)
September 2010
Sun Mon Tue Wed Thu Fri Sat
 << <   > >>
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30    

Reliable Penguin offers Linux Server Migrations, Systems Administration & Programming. Visit our main website at:

http://www.reliablepenguin.com

Search

Bookmark and Share

XML Feeds

blog engine