1 while s/ \s [^b]* \K b (?=a) /B/x; # ^ only start the substitution here # ^ go to the first b # ^ only search second string