in reply to Work-around for variable length look-behind?
1 while s/ \s [^b]* \K b (?=a) /B/x; # ^ only start the substitution here # ^ go to the first b # ^ only search second string [download]
(Update: added the "before a" criterion)