On 10/25/23 10:32, Josef Wolf wrote:
[...]
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.
[...]
You could so something like:
use feature qw(signatures);
sub substitute_lines($contents, $regex, $subst) {
$contents =~ s/$regex/$subst->()/emgr;
}
...
substitute_lines
$data,
qr/^foo (whatever) bar$/,
sub { "bar $1 baz" };
This will pass an anonymous sub routine which will be called from s///
replacement side thanks to the /e modifier that allows code to be
executed there.
Also of some note is that the /r modifier is used so that s/// returns
the resulting string instead of modifying $contents, and being the last
statement, said resulting string is the return value.
--
gordonfish
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/