my @sorted = sort { $scores{$b} <=> $scores{$a} } keys %scores; @sorted = reverse @sorted if condition; for ( @sorted ) { ... }