http://www.perlmonks.org?node_id=1004907


in reply to Replace the nth occurence

You would do well to build a generalized and easy-to-understand way to do this, instead of chicken-scratch solutions that are both non-obvious and basically unmaintainable. Between index and substr you could build a function that loops to find the correct index and then does the replacement; given the input string, the string to be replaced, and the occurrence number. You are almost guaranteed to be happier with this "inefficient" way of doing it, because it is a generalized way of doing something that, no doubt, will wind up being used in a bunch of different situations. CPAN also has thousands of string utilities.