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

Dear Monks,

I wish to perform regex substitutions in a string containing Windows paths. More precisely, eliminate some paths from the string. Could someone help me out with the regex substitution, which does not seem work in the following code ?

I would appreciate if somebody explained what exactly the problem is. I fear it's something very basic that I am missing here..

Thank you in advance !
#!/usr/bin/perl -w use strict; use warnings; my $path = join ';', ( 'D:\aa\bb\cc', 'D:\dd\ee\ff', 'D:\gg\hh\ii', ); my $path_component = 'D:\aa\bb\cc'; print $path, "\n\n"; $path =~ s/$path_component//i; print $path, "\n\n";

Replies are listed 'Best First'.
Re: Problem with regex substitution within windows paths
by Corion (Patriarch) on Jul 08, 2011 at 15:54 UTC

    Your string replacement contains characters that are special to the regex engine. See perlop on \Q resp. quotemeta.

      > characters that are special to the regex engine

      Namely, \, the escape character itself. So you need to escape the escape: \\.

      Thank you Corion ! The code now works :
      #!/usr/bin/perl -w use strict; use warnings; my $path = join ';', ( 'D:\aa\bb\cc', 'D:\dd\ee\ff', 'D:\gg\hh\ii', ); my $path_component = quotemeta( 'D:\aa\bb\cc;' ); print $path, "\n\n"; $path =~ s/$path_component//i; print $path, "\n\n";
      ... and, more importantly, I've now understood what was going wrong...