How to use the / r flag in a Perl regex?

Perl document state:

e  Evaluate 'replacement' as an expression
r  Return substitution and leave the original string untouched.

- Available flags to be used in replacement templates. When I pass the flag to rmy wildcard, it is interpreted as a syntax error. I am running Perl 5.8.8. Is it possible that this is not supported in my version of Perl? Also, can someone provide a working example of how to use a flag and how to call a newly created replacement?

+5
source share
1 answer

Perhaps you should read the docs for 5.8.8? / R added to 5.14!

In 5.8.8 you can do the equivalent

s/foo/bar/r

with

do { (my $s = $_ ) =~ s/foo/bar/; $s }

Examples of using s /// r:

print "abba" =~ s/b/!/rg;         # Prints a!!a

my $new = $old =~ s/this/that/r;  # Leaves $old intact.

my $trimmed = $val =~ s/^\s+//r =~ s/\s+\z//r;
my $trimmed = (($val =~ s/^\s+//r) =~ s/\s+\z//r);  # Same as previous
+15
source

All Articles