in reply to Re: How do I replace a substring (if exists) with a different substring in a string?
in thread How do I replace a substring (if exists) with a different substring in a string?
Note: I found a bug in my earlier answer, since I can't edit it, I am posting this follow up. If the string to replace has the substring you are trying to find, it can get into an endless loop. Here is an updated ansewer:
my $string = '01234567890'; my $find = '0'; my $replace = 'a'; my $pos = index($string, $find); while($pos > -1) { substr($string, $pos, length($find), $replace); $pos = index($string, $find, $pos + length($replace)); }
In this case, an s/// regex is actually 5% faster.
|
---|
In Section
Seekers of Perl Wisdom