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.

Reply via email to