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

Hi,
Here is a snippet of my code:

foreach my $elem (@repos) { (my $repo_name = $elem) =~ s/$svnroot//i; print "$repo_name\n"; }

$svnroot is equal to e:\svn (yes this is on win32).
$elem is equal to e:\svn\firmware\AGV5

so... I'm trying to create a $repo_name that only includes the firmware\AGV5 by replacing the e:\svn with null. Only, it doesn't work. In the search expression, if I replace the $svnroot with s/e:\\svn//i it works.

I've seen numerous examples of using a variable in the search expression... what could I be doing wrong?

TIA,

gheard

20050606 Janitored by Corion: Added formatting

Replies are listed 'Best First'.
Re: search and replace frustration
by thundergnat (Deacon) on Jun 06, 2005 at 14:13 UTC

    You need to put quota-meta assertions around your regex. e:\svn is interpreted as e-colon-space-vn.

    Write your regex as:

    s/\Q$svnroot\E//i;

    Note: this is probably not the best way to do what you are doing, but it answers the question of "Why doesn't this work?"

Re: search and replace frustration
by ikegami (Patriarch) on Jun 06, 2005 at 14:51 UTC

    Since you're searching for a constant string, index is faster than a regexp:

    foreach my $elem (@repos) { my $repo_name = $elem; my $pos = index(lc($repo_name), lc($svnroot)); if ($pos >= 0) { substr($repo_name, $pos, length($svnroot), ''); } print("$repo_name\n"); }

    Or since you probably meant to search for /^\Q$svnroot\E/ (i.e. search for $svnroot at the beginning of the string), this is more precise and even faster:

    foreach my $elem (@repos) { if (lc($svnroot) eq substr(lc($elem), 0, length($svnroot))) { print(substr($elem, length($svnroot)), "\n"); } else { print("$elem\n"); } }