cormanaz has asked for the wisdom of the Perl Monks concerning the following question:

Good afternoon monks. I am trying to do a variable substitution in a regexp that contains a reference to a special variable and it's not working. When I try to do the same substitution directly it works, as illustrated in this simplified example (in reality I'm trying to do this with many different search/replace strings):
$string = "firstword secondword"; print "original: $string\n"; # doesn't work $search = '(second.+)'; $replace = '$1 thirdword'; ($varsub = $string) =~ s/$search/$replace/; print "variable substitution: $varsub\n"; # does work ($direct = $string) =~ s/(second.+)/$1 thirdword/; print "direct: $direct\n";
How do I get perl to recognize the special variable in the $replace string?

Steve

Replies are listed 'Best First'.
Re: Regexp variable substitution of special variable
by davido (Cardinal) on Jun 30, 2005 at 22:24 UTC

    $replace = '$1 thirdword'; ($varsub = $string) =~ s/$search/$replace/;

    Should be replaced with...

    $replace = '$1 . " thirdword"'; ($varsub = $string) =~ s/$search/$replace/ee;

    ...at least that is if you are looking for a solution that is pretty close to what you're attempting.


    Dave

      Both this and diotalevi's code works. Thanks for the suggestions. Is one method superior to the other?
Re: Regexp variable substitution of special variable
by diotalevi (Canon) on Jun 30, 2005 at 22:19 UTC
    Write your replacement this way instead: s/$search/eval qq["$replace"]/e. The key is the /e and the eval using a bit of runtime constructed perl code.

    Thanks to davido for noticing a bug that would prevent my original suggestion from working.

      Another minor comment ... e's stack. s/$search/qq["$replace"]/ee is exactly the same as yours. Which is better is a matter of opinion. :-)

        I think its better to make the second eval explicit and very visible because it is a very different sort of eval from the first /e. So I really, strongly, prefer my version. They're functionally equivalent but you can see that something really, highly unusual is happening in mine. It isn't so visible in yours.