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

Hi,

I'm having trouble with the following code:

$srcroot = "/some/dir"; $destroot = "/some/other/dir"; $srcdir = "/some/dir/with/more/sub/dirs"; ($extra_path = $srcdir) =~ s/^$srcroot//; $destdir = $destroot . $extra_path; print "extra_path: $extra_path\n"; print "destdir: $destdir\n";
This simple demo works fine; $destdir gets set to "/some/other/dir/with/more/sub/dirs". I then read files from $srcdir and write them to $destdir, thus replicating the src directory structure.

However, in my real code, srcdir is read from the filesystem by recursively scanning from the srcroot provided by the user. I've found that the above code breaks if srcdir contains round brackets (and probably other "special" chars too).

For example:

$srcroot = "/some/(dir)"; $destroot = "/some/other/dir"; $srcdir = "/some/(dir)/with/more/sub/dirs"; ($extra_path = $srcdir) =~ s/^$srcroot//; $destdir = $destroot . $extra_path; print "extra_path: $extra_path\n"; print "destdir: $destdir\n";
This prints:

extra_path: /some/(dir)/with/more/sub/dirs destdir: /some/other/dir/some/(dir)/with/more/sub/dirs
Can anyone suggest a fix for this or an alternative means to achieve what I'm trying to do?

Thanks,

R.

--

Robin Bowes | http://robinbowes.com

Replies are listed 'Best First'.
Re: regex matches with () in strings
by Tanktalus (Canon) on Feb 17, 2005 at 00:26 UTC
    ($destdir = $srcdir) =~ s/^\Q$srcroot/$destroot/;

    Check out perlre for more info on all the regular expression special characters. It's like a language all to itself in there! :-)

Re: regex matches with () in strings
by sh1tn (Priest) on Feb 17, 2005 at 02:09 UTC
    ($extra_path = $srcdir) =~ s/^\Q$srcroot\E//;
      I was just coming back to say I'd found \Q \E in perldoc perlop but it appears two of you have beat me to it!

      Thanks!

      R.

      --

      Robin Bowes | http://robinbowes.com

Re: regex matches with () in strings
by gopalr (Priest) on Feb 18, 2005 at 05:01 UTC

    Hi,

    If you want to escape all non-word characters, use the \Q and \E string metacharacters or the quotemeta function.

Re: regex matches with () in strings
by tirwhan (Abbot) on Feb 17, 2005 at 10:41 UTC
    Just for completeness:
    $srcroot=quotemeta("/some/(dir)");
    is functionally equivalent to the above proposed solutions, albeit more verbose and (possibly) easier to understand for those less familiar with regexes.