in reply to How do I replace a substring (if exists) with a different substring in a string?
You can use substr, length, and index inside a while loop to do what you want:
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)); }
IMHO you can't beat the following for readability:
$string =~ s/\Q$find\E/$replace/g;
|
---|
Replies are listed 'Best First'. | |
---|---|
(dkubb) Re: (3) Answer: How do I replace a substring (if exists) with a different substring in a string?
by dkubb (Deacon) on Jul 22, 2001 at 02:00 UTC | |
Re: Answer: How do I replace a substring (if exists) with a different substring in a string?
by kocetoo (Novice) on Jun 28, 2016 at 12:38 UTC |
In Section
Seekers of Perl Wisdom