RE: Using qr// with substitution and group-interpolation in the substitution part

Claude Brown via beginners <[email protected]> Wed, 25 Oct 2023 21:07:04 +0000
Newsgroups gmane.comp.lang.perl.beginners
Message-ID <SYBP282MB252706DC81FDC93A9737547DC7DEA@SYBP282MB2527.AUSP282.PROD.OUTLOOK.COM>
Josef,

Inspired by Levi's “eval” idea, here is my solution:

sub substitute_lines {
    my ($contents, $regex, $subst) = @_;
    eval "\$contents =~ s/$regex/$subst/g";
    return $contents;
}

$data = "foo whatever bar";
$data = &substitute_lines($data, qr/^foo (whatever) bar$/m, 'bar $1 baz');
print "$data\n";

The differences:
- escaped the "$" so the eval gets a literal "$contents"
- didn't escape "$" so the eval receives the value of $regex and $subst
- moved the "g" into the sub as it has no meaning for a qr//
- removed the "m" from the sub as it best left with the original qr//
- added "$data = ..." to get back the value from the subroutine

Cheers,

Claude.