Perl, the substitute operator s
Archive - Originally posted on "The Horse's Mouth" - 2007-06-08 07:02:31 - Graham EllisIn Perl, the s (or substitute) operator allows you to match a regular expression and replace the part of your incoming string that matched with another string. Your incoming string should be specified to the left of an =~ operator and is changed in situ. For example:
$sample = "The cat sat on the mat";
$sample =~ s/.at/dog/;
Would replace cat (as "." means any character) with dog. It would stop at that point, as the s operator only changes a single occurence unless a g for global modifier is added on the end. So
$sample = "The cat sat on the mat";
$sample =~ s/.at/dog/g;
Would give you The dog dog on the dog
• if you don't specify the variable that s is to work on, it works on the contents of $_
• if you add an e modifier, it performs the output string as a perl expression and substitues in the result.
• if you specify or in the output string, you'll mean the first captured part of the incoming string that matched, and so on.
• if you use the value returned by the substitute operator, you'll find that it contains the number of changes made.
There's an example of all of these features just added to our web site here