use strict; use warnings; my $anchor = 1; # This is the basic element of the pairs we are looking for my %results; # The final results will be found in this hash foreach () { my %hash; foreach (split) { # Put the array into a hash $hash{$_}=1; } if ($hash{$anchor}) { # Only process the hash if the anchor is present foreach (keys %hash) { # increment the frequencies in the results-hash ++$results{$_} unless $_==$anchor; # but omit the anchor or the sort will not work! } } } for my $x(sort {return $results{$b} <=> $results{$a}} keys %results) { print "$x = $results{$x}\n"; } __DATA__ 2 4 5 7 8 10 1 2 5 6 7 9 2 6 7 8 9 10 1 3 5 10 1 3 4 5 6 8 9 1 2 4 6 1 2 4 5 7 10 1 3 4 6 7 8 9