Click to See Complete Forum and Search --> : Sorting Hashes problem


kimskams80
06-06-2009, 04:56 AM
Hi

I am populating a Hash with some Keys (document number) and then with its score (value) ..

$hash1 {$doc1} = $simple;

later on i m sorting it as:

foreach $value (sort {$hash1{$b} cmp $hash1{$a} }
keys %hash1)
{
print "$value $hash1{$value}\n";
print output1 "$value $hash1{$value}\n";
}

I get the results sorted but not really correct..



BLOG06-20051212-031-0003871075 4.14992
BLOG06-20060110-011-0015588619 4.13509
BLOG06-20051222-007-0004908546 4.10373
BLOG06-20060107-024-0024447600 4.08113
BLOG06-20060119-051-0021895341 4.03272
BLOG06-20060204-022-0003438131 4.02714
BLOG06-20060106-002-0025536939 36.60849
BLOG06-20051225-070-0022703883 36.52406
BLOG06-20051210-115-0002949561 34.54609
BLOG06-20051210-115-0002611122 34.54609
BLOG06-20060125-019-0017346222 33.96004
BLOG06-20060203-020-0000653255 33.21165
BLOG06-20060106-013-0032881417 33.0934
BLOG06-20060106-002-0025077337 31.82231
BLOG06-20051209-072-0007165450 3.99225
BLOG06-20060212-003-0003166869 3.98698
BLOG06-20060204-002-0008217091 3.97136



I mean there is a series of good sorted data and when a bigger number (with two digits on right of decimal) appears then problem.. any problem with coding??

thanks

perl_diver
06-06-2009, 05:05 PM
'cmp' compares and sorts in ASCII order, if you want numeric order use '<=>'


foreach $value (sort {$hash1{$b} <=> $hash1{$a} }
keys %hash1)
{
print "$value $hash1{$value}\n";
print output1 "$value $hash1{$value}\n";
}


See sort() for more details:

http://perldoc.perl.org/functions/sort.html