my @site1 = qw( AATKKM aatkkm ); my @site2 = qw( GGGGGG gggggg ); my %counts; for my $site1 ( @site1 ){ for my $site2 ( @site2 ) { $counts{ substr( $site1, $_, 1 ) . substr( $site2, $_, 1 ) }++ for 0 .. min( length( $site1 )-1, length( $site2 )-1 ); } } print Dumper \%counts;