7.5 Substitutions
We've already talked about the simplest form of the
substitution operator:
If you want the replacement to operate on
all possible matches instead of just the first match, append a
$_ = "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
An
As with the match operator, an alternate delimiter can be selected if the slash is inconvenient. Just use the same character three times:[ 7 ]
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 |
|