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


Book HomeLearning Perl, 3rd EditionSearch this book

9.6. Substitutions with s///

If you think of the m// pattern match as being like your word processor's "search" feature, the "search and replace" feature would have to be Perl's s/// substitution operator. This simply replaces whatever part of a variable[205] matches a pattern with a replacement string:

[205]Unlike m//, which can match against any string expression, s/// is modifying data that must therefore be contained in what's known as an lvalue. This is nearly always a variable, although it could actually be anything that could be used on the left side of an assignment operator.

$_ = "He's out bowling with Barney tonight.";
s/Barney/Fred/;  # Replace Barney with Fred
print "$_\n";

If the match fails, nothing happens, and the variable is untouched:

# Continuing from above; $_ has "He's out bowling with Fred tonight."
s/Wilma/Betty/;  # Replace Wilma with Betty (fails)

Of course, both the pattern and the replacement string could be more complex. Here, the replacement string uses the first memory variable, which is set by the pattern match:

s/with (\w+)/against $1/;
print "$_\n";  # says "He's out bowling against Fred tonight."

Here are some other possible substitutions. (These are here only as samples; in the real world, it would not be typical to do so many unrelated substitutions in a row.)

$_ = "green scaly dinosaur";
s/(\w+) (\w+)/$2, $1/;  # Now it's "scaly, green dinosaur"
s/^/huge, /;            # Now it's "huge, scaly, green dinosaur"
s/,.*een//;             # Empty replacement: Now it's "huge dinosaur"
s/green/red/;           # Failed match: still "huge dinosaur"
s/\w+$/($`!)$&/;        # Now it's "huge (huge !)dinosaur"
s/\s+(!\W+)/$1 /;       # Now it's "huge (huge!) dinosaur"
s/huge/gigantic/;       # Now it's "gigantic (huge!) dinosaur"

There's a return value from s///; it's true if a substitution was successful; otherwise it's false:

$_ = "fred flintstone";
if (s/fred/wilma/) {
  print "Successfully replaced fred with wilma!\n";
}


Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.