use strict; my @nonmatched = qw(TACTCAGGAG TACTCGGGAG); my $difference = $nonmatched[0] ^ $nonmatched[ 1 ]; # Replace all zeroes (= matches) by the original string: $difference =~ s/\0/substr($nonmatched[0],pos($difference),1)/ge; # Replace the "weird" parts with the proper pairs my %pairs = ( 'C' ^ 'T' => '(C,T)', 'A' ^ 'G' => '(A,G)', ); $difference =~ s/(.)/$pairs{$1} || $1/ge; print $difference;