To replace all occurrences of a substring in a string in Perl, you can use the s///g
operator.
In this example,
$str
.s///g
operator with the substring to be replaced, the replacement string, and the input string as arguments.s///g
operator replaces all occurrences of the substring.$str = 'Hello World Hello';
$str =~ s/Hello/Hi/g;
print $str;
Hi World Hi
In this example,
$str
.s///g
operator with a regular expression to match the character 'o', and the replacement character as arguments.s///g
operator replaces all occurrences of the character.$str = 'Hello World Hello';
$str =~ s/o/X/g;
print $str;
HellX WXrld HellX
In this tutorial, we learned How to Replace All Occurrences of a Substring in a String in Perl language with well detailed examples.