I like this solution, because it's so simple and efficient:
#!/usr/bin/perl -w
use strict;
my @lines = <DATA>;
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]/ an
+d /$uniq[$j]/ } foreach @lines;
}
}
print map "$_ : $count{$_}\n", # print the pairs in s
+orted order
sort {$count{$a} <=> $count{$b}}
keys %count;
__DATA__
dog monkey cat
cat ball stone
monkey iron cat zoo
(NB see parent node)