while (...) { $balances{$cust} += $bal * $fx_rates->{$ccy}; } ... # Find the customers whose total balance is greater than $500000000.00 my %top_balances; my $top_threshold = 510000000.00; # default threshold $0.5 bil my $top_count; # keep a count of how many found do { # lower threshold by 10 million every time $top_threshold -= 10000000.00; die ("This is impossible, the data has error!") if ($top_threshold < 0.00) $top_count = 0; while ( my ($cust, $balance) = each %balances ) { if ($balance > $top_threshold) { $top_balances{$cust} = $balance; $top_count++; } } } while ($top_count < $nth); # Safety check - how big is our list? Is it > n? if ($VERBOSE) { print "$top_count customers have ", "balances greater than \$${top_threshold}.\n"; } # Sort only the top customers by descending order of balance my @sorted_cust_list = reverse map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [$_, $top_balances{$_}] } keys %top_balances;