for (1,2,5,6){ foreach $ar (@{$D[$_]}){ $hash{$ar}++; } } # sort %hash #pick top two