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

Hello Monks!

I am building a little graphical tool to search and replace strings in text files in an interactive manner. For the replace function, I would like the ability to capture substrings in order to reuse them in the replace string. So far I did not find a way to use the $1 when it is not hardcoded.
This would be an example of user input :
$string1='sometext(.*)something(.*)'; $string2='$1:$2';
This would be the replace statement.
$mystring =~ s/$string1/$string2/g;

I have tried a couple of ways but I don't seem to be able to find a right way. Maybe I missed something very basic or maybe I should use some module to do this.
I am pretty new to Perl so I will not be annoyed if I am directed to a piece of documentation :D

Can please someone advise?
Thanks Zylot

Replies are listed 'Best First'.
Re: Capturing in interactive replace?
by graff (Chancellor) on Feb 20, 2008 at 02:10 UTC
    You need to use a string eval, and make sure to escape the dollar-sign on "$mystring":
    $string1 = 'sometext(.*)something(.*)'; $string2 = '$1:$2'; $mystring = "sometext--blahblah--something--foobar--"; eval "\$mystring =~ s/$string1/$string2/"; print "$mystring\n";
    That is: $string1 and $string2 will be interpolated before being passed to eval, and $mystring will not be interpolated. In the example above, eval will see:
    $mystring =~ s/sometext(.*)something(.*)/$1:$2/;
    and that is what will be executed within the eval.
      Thank you, that does really help!

      Thanks
      Zilot