On 23/06/2011 10:36, Irfan Sayed wrote:
> Hi,
> 
> i need to sort hash in descending order.
> but the issue is , in hash, i have key as integer value and the value 
> associated with that key is string
> 
> so when i do sort it does not really sort the hash on the key level
> 
> 
> i used follwoing code
> 
> foreach my $key (sort { $hash_fin{$b}<=>  $hash_fin{$a} } keys %hash_fin) {
> print "$key =>  $hash_fin{$key}\n";
> 
> }
> 
> the unsorted hash is :
> 12 =>  20110622-035007-134
> 131 =>  20110622-002139-131
> 107 =>  20110621-215838-127
> 13 =>  20110622-035007-134
> 129 =>  20110621-235900-129

It looks like you want to sort the hash elements by value?

For string data you must use the string comparator 'cmp' instead of the
numeric comparator. Take a look at the program below.

HTH,

Rob


use strict;
use warnings;

my %hash_fin = (
  12  => '20110622-035007-134',
  131 => '20110622-002139-131',
  107 => '20110621-215838-127',
  13  => '20110622-035007-134',
  129 => '20110621-235900-129',
);

foreach my $key (sort { $hash_fin{$b} cmp $hash_fin{$a} } keys %hash_fin) {
  printf "%-3d => '%s'\n", $key, $hash_fin{$key};
}

**OUTPUT**

13  => '20110622-035007-134'
12  => '20110622-035007-134'
131 => '20110622-002139-131'
129 => '20110621-235900-129'
107 => '20110621-215838-127'

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to