Re: Using qr// with substitution and group-interpolation inthesubstitution part
gordonfish <[email protected]> Tue, 21 Nov 2023 20:26:46 -0800
| Newsgroups | gmane.comp.lang.perl.beginners |
|---|---|
| Message-ID | <[email protected]> |
On 11/21/23 20:08, gordonfish wrote:
> 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.
> [...]
---Reposting due to code indents being eaten---
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: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/