next up previous
Next: Summary Up: Regular Expressions Previous: Capturing


Substitution

Finally, we take a brief look at the substitution capabilities of perl. Substitution is most simply described in the analogy to search and replace operation in many text editors. The substitution operator (s/<find>/<replace>/) has two parts. The first part specifies a regular expression to find, and the second part specifies some text to replace it with. See if you can follow the following example.

$text = "I built my house on the sand.";
$text =~ s/sand/rock/;
print "$text\n";
# prints "I built my house on the rock."

Basically, the regular expression stops when it matches the word ``sand'' and then replaces that match with the word ``rock''. If you wanted to, say, change all the o's to 0's in a string, then you'd have to use the `
g
'' modifier to tell Perl to keep going after it finds one match.

$text = "more tomes roam rome";
$text =~ s/o/0/g;
print "$text\n";
# prints "m0re t0mes r0am r0me"



saville stephen a 2003-01-05