[Chapter 7] 7.5 Substitutions
Author: Randal L. Schwartz, Erik Olson & Tom Christiansen
Date: 1999-07-02T01:33:46Z

#

| Chapter 7 Regular Expressions |

## 7.5 Substitutions

We've already talked about the simplest form of the substitution operator: `s/old-regex/new-string/`. We can now discuss a few variations of this operator.

If you want the replacement to operate on all possible matches instead of just the first match, append a `g` to the substitution, as in:

    $_ = "foot fool buffoon";
    s/foo/bar/g; # $_ is now "bart barl bufbarn"

The replacement string is variable interpolated, allowing you to specify the replacement string at runtime:

    $_ = "hello, world"
    $new = "goodbye";
    s/hello/$new/; # replaces hello with goodbye

Pattern characters in the regular expression allow patterns to be matched, rather than just fixed characters:

    $_ = "this is a test";
    s/(\w+)/<$1>/g; # $_ is now "<this> <is> <a> <test>"

Recall that `$1` is set to the data within the first parenthesized pattern match.

An `i` suffix (either before or after the `g`, if present) causes the regular expression in the substitute operator to ignore case, just like the same option on the match operator described earlier.

As with the match operator, an alternate delimiter can be selected if the slash is inconvenient. Just use the same character three times:[7]

> [7] Or, use two matching pairs if a left-right pair character is used.

    s#fred#barney#; # replace fred with barney, like s/fred/barney/

Also as with the match operator, you can specify an alternate target with the =~ operator. In this case, the selected target must be something you can assign a scalar value to, such as a scalar variable or an element of an array. Here's an example:

    $which = "this is a test";
    $which =~ s/test/quiz/; # $which is now "this is a quiz"
    $someplace[$here] =~ s/left/right/; # change an array element
    $d{"t"} =~ s/^/x /; # prepend "x " to hash element

7.4 More on the Matching Operator |  | 7.6 The split and join Functions