summaryrefslogtreecommitdiff
path: root/pod/perlretut.pod
diff options
context:
space:
mode:
authorDavid Caldwell <david@porkrind.org>2009-11-23 17:24:25 -0800
committerDavid Caldwell <david@porkrind.org>2010-05-22 02:28:22 -0700
commit4f4d7508b0c2c114e5f52420e0e87a853c5f642a (patch)
tree008d80915d83e246892b83fa06e46a3b2e21c6bf /pod/perlretut.pod
parentdd9035cd5bdeced1187df399d27d526f3b30194b (diff)
downloadperl-4f4d7508b0c2c114e5f52420e0e87a853c5f642a.tar.gz
Add s///r (non-destructive substitution).
This changes s/// so that it doesn't act destructively on its target. Instead it returns the result of the substitution (or the original string if there was no match). In addition this patch: * Adds a new warning when s///r happens in void context. * Adds a error when you try to use s///r with !~ * Makes it so constant strings can be bound to s///r with =~ * Adds documentation. * Adds some tests. * Updates various debug code so it knows about the /r flag. * Adds some new 'r' words to B::Deparse.
Diffstat (limited to 'pod/perlretut.pod')
-rw-r--r--pod/perlretut.pod25
1 files changed, 25 insertions, 0 deletions
diff --git a/pod/perlretut.pod b/pod/perlretut.pod
index 0ff743838c..a9a3372636 100644
--- a/pod/perlretut.pod
+++ b/pod/perlretut.pod
@@ -1714,6 +1714,31 @@ occurrences of the regexp on each line and the C<s///o> modifier to
compile the regexp only once. As with C<simple_grep>, both the
C<print> and the C<s/$regexp/$replacement/go> use C<$_> implicitly.
+If you don't want C<s///> to change your original variable you can use
+the non-destructive substitute modifier, C<s///r>. This changes the
+behavior so that C<s///r> returns the final substituted string:
+
+ $x = "I like dogs.";
+ $y = $x =~ s/dogs/cats/r;
+ print "$x $y\n";
+
+That example will print "I like dogs. I like cats". Notice the original
+C<$x> variable has not been affected by the substitute. The overall
+result of the substitution is instead stored in C<$y>. If the
+substitution doesn't affect anything then the original string is
+returned:
+
+ $x = "I like dogs.";
+ $y = $x =~ s/elephants/cougars/r;
+ print "$x $y\n"; # prints "I like dogs. I like dogs."
+
+One other interesting thing that the C<s///r> flag allows is chaining
+substitutions:
+
+ $x = "Cats are great.";
+ print $x =~ s/Cats/Dogs/r =~ s/Dogs/Frogs/r =~ s/Frogs/Hedgehogs/r, "\n";
+ # prints "Hedgehogs are great."
+
A modifier available specifically to search and replace is the
C<s///e> evaluation modifier. C<s///e> wraps an C<eval{...}> around
the replacement string and the evaluated result is substituted for the