Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Pass Matched Variable into Regex Replace Variable

by deMize (Monk)
on Dec 17, 2010 at 18:06 UTC ( [id://877671]=perlquestion: print w/replies, xml ) Need Help??

deMize has asked for the wisdom of the Perl Monks concerning the following question:

Question: I'm curious how to interpolate a matched variable ($1) into the replacement variable of the regex.
my $text = "Other Text. From {foo bar foo bar}"; my $pattern = 'From \{(.*?)\}'; my $replace = 'To {$1}'; $text =~ s/$pattern/$replace/ge; # text should equal "Other Text. To {foo bar foo bar }";
I was able to accomplish it by creating an external function and passing $1 as a parameter to that function, but I figure there's an easier way. Also, I was not able to create and call the inline function in one step.

Please no comments like, "why don't you $text=~s/From/To/"?


As always, I appreciate the help.


Demize




Downvotes are welcome, just please comment as to why you are doing them. Thank you.

Replies are listed 'Best First'.
Re: Pass Matched Variable into Regex Replace Variable
by Anonyrnous Monk (Hermit) on Dec 17, 2010 at 18:19 UTC

    You could do

    ... my $replace = '"To {$1}"'; $text =~ s/$pattern/$replace/gee; # eval twice
      I feel like I've tried that and it didn't work.

      perl -e '$t="begin{foobar}";$p="begin{(.*?)}";$r="\"end{\$1}\""; $t=~s/$p/$r/gee; print "$t\n\n"'
      #Output: end{foobar}

      Perhaps I'm doing something wrong? Edit:I didn't escape the dollar sign in the variable. The suggestion works. I'll apply it to my program and see if everything works :) Thank you!
        $r="\"end{$1}\"";

        The double quotes interpolate the $1. Use $r=q("end{$1}") in this case.

Re: Pass Matched Variable into Regex Replace Variable
by AnomalousMonk (Archbishop) on Dec 17, 2010 at 21:27 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://877671]
Approved by moritz
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (7)
As of 2024-03-28 08:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found