Perl replace substring

Lets say you have got a string in Perl and you want to replace just a part of it. How can you do it ?
Let’s go through the following methods without any delay 🙂

Method 1 : Using substr function

my $string = "Tea is good with milk.";
substr($string, 4, 2) = "might be";
print $string;

Output : Tea might be good with milk.

W have replaced 2-charecter length “is” with “might be”.

Method 2 : Using s/FIND/REPLACE/ syntax.

# syntax (NOTE: this overwrites your original string)

my $string = "Tea is good with milk.";
$string =~ s/tea/coffee/ig;
print $string;

Output : coffee is good with milk.

Here we used two flags as well.
i : case-insensitive
g : replace all occurances.

Hope the above methods works for you. Happy Learning and get back to us Anytime.

Realted Posts : Perl http request