home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

7.5 Substitutions

We've already talked about the simplest form of the substitution operator: s/old-regex/new-string/ . It's time for 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 run-time:

$_ = "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 ]

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

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

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