Perl: Can I store backlinks (and not their values) in variables?

I would like to do something like this:

my $text = "The owls are not what they seem."; my $pattern = '(\s+)'; my $replacement = '-$1-'; $text =~ s/$pattern/$replacement/g; 

$ text should be: The- -owls- -are- -not- -what- -yy -seem.

But, of course, this is more like: "$ 1-ow-1 dollar" - $ 1-not- $ 1-what- $ 1-they- $ 1-seems.

I tried all kinds of backlinks ($ 1, \ 1, \ g {1}, \ g1), and all of them do not work. The / e modifier does not work either. Is this even possible?

The goal is to change the text inside the object using a string: $ object-> replace ('(.) Oo', '$ 1ar')

Any other ideas how to do this?

Many thanks.

+6
regex perl
source share
3 answers

You can define and then expand the lines using /ee :

 my $text = "The owls are not what they seem."; my $pattern = '(\s+)'; my $replacement = q{"-$1-"}; $text =~ s/$pattern/$replacement/eeg; 

From perldoc perlop :

e Rate the right side as an expression.

ee Rate the right side as a string, then evaluate the result

However, I would feel safer with

 my $replacement = sub { "-$1-" }; $text =~ s/$pattern/$replacement->()/eg; 

But it all depends on the context in which you do it.

+12
source share

Sinan Ünür's solution will work, but at some point it still requires the replacement string to be literal inside the program. If this replacement string comes from the data, you will need to do something a bit strange:

 sub dyn_replace { my ($replace) = @_; my @groups; { no strict 'refs'; $groups[$_] = $$_ for 1 .. $#-; # the size of @- tells us the number of capturing groups } $replace =~ s/\$(\d+)/$groups[$1]/g; return $replace; } 

and then use it like

 $text =~ s/$pattern/dyn_replace($replacement)/eg; 

Note that this also avoids eval and allows the use of modifiers such as / g. The code is taken from this Perl Monks node , but I wrote that node, so that's fine :)

+3
source share

$ text = ~ s / $ pattern / - $ 1- / g;

-3
source share

All Articles