Memory Refresh

Search and replace


In the construct $var =~ s/regex/replacement/ 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. We use word-boundary metacharacter. $var = "Jeffrey Friedl"; $var =~ s/\bJeff\b/Jeffrey/; print $var; #Outputs: Jeffrey Friedl - not Jeffreyrey Friedl

Global replacement

The search and replace is done just once. 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 prices 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
Comments ...