Last update:   29-10-2021

Replace in Perl

The text matched (if any) is replaced by replacement.
$var = "Jeff Friedl";

$var =~ s/Jeff/Jeffrey/;

print $var; //Outputs: Jeffrey Friedl

Word boudary

If we did that search/replace again, it would end up with Jeffreyrey Friedl.
$var = "Jeffrey Friedl";

$var =~ s/\bJeff\b/Jeffrey/; // word boundary

print $var; 
    #Outputs: Jeffrey Friedl - not Jeffreyrey Friedl
Global Replace    (2/3)

Global replace

In order to find and replace all matches we use /g global replacement modifier.
$var = "Jeff is Jeff Friedl";
$var =~ s/\bJeff\b/Jeffrey/g;
print $var; 
    #Outputs: Jeffrey is Jeffrey Friedl
Stock Example    (3/3)

Stock example

We want to remove digits from stock proces, so 12.37500000392 is reduce to 12.375, yet 37.500 is reduced to 37.50 Metacharacter \d matches a digit, while [1-9]? removes a third posible zero (if any).
$price = "12.37500000392";
$price =~ s/(\d+.\d\d[1-9]?)\d*/$1/;
print $price ."n";
    #Outputs: 12.375

$price = "37.500";
$price =~ s/(\d+.\d\d[1-9]?)\d*/$1/;
print $price ."n"; 
    #Outputs: 37.50
... 3 lines

        A B C D E F