#!/usr/bin/perl -w use strict; my @lines = ; my (%words, %count); @words{map {split ' '} @lines} =1; my @uniq = keys %words; # create list of unique words foreach my $i (0 .. $#uniq - 1) { foreach my $j ($i+1 .. $#uniq) { # count the pairs do { $count{"$uniq[$i] $uniq[$j]"}++ if /$uniq[$i]/ and /$uniq[$j]/ } foreach @lines; } } print map "$_ : $count{$_}\n", # print the pairs in sorted order sort {$count{$a} <=> $count{$b}} keys %count; __DATA__ dog monkey cat cat ball stone monkey iron cat zoo