http://www.perlmonks.org?node_id=1052987

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

Hello Monks,

I want to replace a substring (relative path to a c-sources) in a string with another string (fullpath to sources) but it's not working at all.. I have no idea why?

Here my code:

use strict; use warnings; use diagnostics; #For testing only a pseudo workspacepath my $Workspace = 'Workspace\\'; #This string has the substring which i want to repalce. my $string = '"_out\Dem_Deb_Cfg.h", line 189: warning #47-D: incompati +ble redefinition of '; if($string=~m/(\[[\S]+\.c\]|\[[\S]+\.h\]|\[[\S]+\.cpp\]|"[\S]+\.c"|"[\ +S]+\.h"|"[\S]+\.cpp")/i){ my $identifier = $1; chop($identifier); my $search = substr($identifier,1); my $replace = $Workspace.$search; if( not($string =~s#$search#$replace#)){ print"does not work :-( \n"; } }
Any help is highly welcome!
Best regards
Tobias

Replies are listed 'Best First'.
Re: Regex match inside quotes doesn't work
by choroba (Cardinal) on Sep 09, 2013 at 09:31 UTC
    $search contains backslashes that should not be interpreted as special characters. Use \Q to quote the special characters:
    if (not $string =~ s/\Q$search/$replace/) {

    Note that / can be used as the delimiter, since neither the pattern nor the replacement contain literal slashes.

    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Regex match inside quotes doesn't work
by Anonymous Monk on Sep 09, 2013 at 09:32 UTC
      Yes.. super!
      Sorry that i forgot to comment the regex!

      Thanks a lot!
      Tobias