use strict; use warnings; my $str1 = "ABCXXFGH"; my $str2 = "XXCDEFGH"; my $str3 = "XXCXXFGH"; my ($str_to_retain) = $str2 =~ /(\w\w\w).*/; my ($replacement) = $str1 =~ /\w\w\w(.*)/; my $replaced_str = $str_to_retain.$replacement; print "$str3\n$replaced_str\n";