tags:

views:

45

answers:

2

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?

A: 

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
Greg Bacon
+2  A: 

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;
}
theraccoonbear
I think I'll want to tweak this a bit to allow the use of more than one capture buffer, but I think this is the way to go.
Ryan Olson