my $pchr = "KQRBNP"; my $w1 = "QRKPNBNBQRK"; my $w2 = ""; for my $L ( split //, $pchr ){ $w1 =~ m/$L(?{ $w2 .= $L })(*FAIL)/; } print "$w1 -> $w2\n"