That's a fun question, Josef! I don't think you can pass a replacement phrase around, so this is all I came up with:
sub substitute_lines { my ($contents, $subst) = @_; $contents = $subst->($contents); return $contents; } my $data = "foo whatever bar"; print(substitute_lines($data, sub { $_[0] =~ s/^foo (whatever) bar$/bar $1 baz/mgr } )); I'd be very pleased if someone could come up with a more elegant solution. On Wed, Oct 25, 2023 at 6:34 PM Josef Wolf <j...@raven.inka.de> 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 > j...@raven.inka.de > > -- > To unsubscribe, e-mail: beginners-unsubscr...@perl.org > For additional commands, e-mail: beginners-h...@perl.org > http://learn.perl.org/ > > >