# ... original code for ((sort { $counted{$b} <=> $counted{$a} } keys %counted)[0..2]) { # ... etc. }