my %count_of; while () { chomp; # sort the words so I don't have "cat-dog" and "dog-cat" my @words = sort split; foreach my $i ( 0 .. $#words - 1 ) { foreach my $j ( $i+1 .. $#words ) { $count_of{ $words[$i] . q{-} . $words[$j] }++; } } } my $top_pair = ( sort { $count_of{$a} <=> $count_of{$b} } keys %count_of )[-1]; print "$top_pair ($count_of{$top_pair})\n"; __DATA__ dog monkey cat cat ball stone monkey iron cat zoo