Re: Using qr// with substitution and group-interpolation in the substitution part
[email protected] (Andy Bach) Wed, 25 Oct 2023 13:43:45 -0500
| Newsgroups | perl.beginners |
|---|---|
| Message-ID | <CACV6rWL1E3SizoSJg2ss7bKNwQaAkT8OXqPEPQM7g6csp7zbJg@mail.gmail.com> |
escape (or double escape) the $, maybe? substitute_lines($data, qr/^foo (what) bar$/, 'bar \$1 baz'); Sorry, I can't test right now. Note, you don't need, nor want the & to make a sub call - it has other implications you aren't using. https://stackoverflow.com/questions/1347396/when-should-i-use-the-to-call-a-perl-subroutine On Wed, Oct 25, 2023 at 12:34 PM Josef Wolf <[email protected]> wrote: > Hallo all, > > maybe this is not exactly a beginner question, but I could not find an > appropriate mailing list (all other lists seem to be developer realted). > > > Basically, I want to do the same as > > > $data =~ s/^foo (whatever) bar$/bar $1 baz/mg; > > > but with a different interface (because it has to be embedded into a bigger > project), So I have come with this; > > > sub substitute_lines { > my ($contents, $regex, $subst) = @_; > $contents =~ s/$regex/$subst/mg; > return $contents; > } > } > > &substitute_lines ($data, qr/^foo (whatever) bar$/mg, 'bar $1 baz'); > > > Which (mostly) works as expected. Unfortunately, this won't interpolate the > matched group $1. > > Experiments which also do not work: > > > &substitute_lines ($data, qr/^foo (whatever) bar$/mg, "bar $1 baz"); > # obviously, $1 is interpolated _before_ re-match is done > > > &substitute_lines ($data, qr/^foo (whatever) bar$/mge, '"bar $1 baz"'); > # /e modifier not accepted > > Any hints? > > -- > Josef Wolf > [email protected] > > -- > To unsubscribe, e-mail: [email protected] > For additional commands, e-mail: [email protected] > http://learn.perl.org/ > > > -- a Andy Bach, [email protected] 608 658-1890 cell 608 261-5738 wk