Ryan Olson
Ryan Olson

Reputation: 2826

Using capture buffers in a Perl regular expression stored in a variable

I am receiving the left and right sides of a regular expression replacement as the arguments to a function. I want my users to be able to use capture buffers, but it doesn't work the way I'm trying to do it.

my $string = "This is my string";

$string = regex_replace($string,'is (my) string','$1');

print "$string\n";

sub regex_replace {
    my ( $string,$left,$right ) = @_;

    $string =~ s/$left/$right/gsm;

    return $string;
}

Executing this outputs "This $1" instead of the "This my" I am trying to get. Is there any way to accomplish what I am trying to do here?

Upvotes: 2

Views: 593

Answers (2)

theraccoonbear
theraccoonbear

Reputation: 4337

If you want to avoid the use of eval...

my $string = "This is my string";

$string = regex_replace($string,'is (my) string','$1');

print "$string\n";

sub regex_replace {
    my ( $string,$left,$right ) = @_;

    $string =~ /$left/g;
    $rv = $1;
    $right =~ s/\$1/$rv/;

    $string =~ s/$left/$right/gsm;

    return $string;
}

Upvotes: 2

Greg Bacon
Greg Bacon

Reputation: 139551

In regex_replace, you could use

eval "\$string =~ s/$left/$right/gsm";

but eval STRING gives people the heebie-jeebies.

With your example, the output is

This my

Upvotes: 0

Related Questions