foreach $keyscore (sort { $totalscoreinv{$keyscore}{$b}<=>$totalscoreinv{$keyscore}{$a} } keys %totalscoreinv) { ... }