my %hit; foreach my $t (@term) { my @doc = $documents_mentioning{$t}; $hit{$_}++ for (@doc); } # Filter (keys %hits) by # of hits (at least 2), then sort. my @res = sort { $hit{$b} <=> $hit{$a} } (grep {$hit{$_} >= 2} keys %hit);