Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the /r flag in Perl regex?

Tags:

regex

perl

The Perl doc states:

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

are available flags to be used in replacement patterns. When I pass the r flag to my substitution pattern, it gets interpreted as a syntax error. I am running Perl 5.8.8. Is it possible it is not supported in my version of Perl? Also, can someone provide a working example of how to use the flag and how to call the newly created replacement?

like image 960
user1671989 Avatar asked Sep 14 '12 16:09

user1671989


1 Answers

Perhaps you should be reading the docs for 5.8.8, then? /r was added to 5.14!

In 5.8.8, you can do the equivalent of

s/foo/bar/r

with

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

Sample usages of 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
like image 105
ikegami Avatar answered Sep 20 '22 22:09

ikegami