use Data::Dumper; my %pairs = (); while (<>) { chomp; my @found = split; for my $k1 ( @found ); for my $k2 ( @found ) { if ( $k2 gt $k1 ) { # ensuring each pair is counted once only for the line $pairs{ $k1 }{ $k2 }++; } } } } print Dumper \%pairs;