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

I'm trying to use grep to compare a directory path such as C:\apps\c++\application with an array of certain file types (e.g. .cpp, .hpp etc) residing on the hard drive, some of which are in the C:\apps\c++\application directory.

The line:
@fileList = grep{/$dirPath/} @allFiles;
works for directories which do not have the plus symbol in their path but not for ones which do. I've tried escaping the plus characters so in effect it's doing:

grep {/c:/apps/c\+\+/application/} c:/apps/c++/application/myfile.cpp

but none of the files in the C++ directory are being returned and if I unescape the "+" I get an error saying "nested quanitfiers in regex"

Any help would be greatly appreciated

Thanks
Steve

Replies are listed 'Best First'.
Re: using grep with multiple "+"
by zejames (Hermit) on Sep 14, 2004 at 13:10 UTC
    Protect your path by using \Q \E :

    my $dirPath = 'c:\apps\c++\application'; print grep { /\Q$dirPath\E/ } ('c:\apps\c++\application\myfile.cpp');
    Then, the + won't be interpreted in the regular expression.

    Kind regards

    --
    zejames
Re: using grep with multiple "+"
by ihb (Deacon) on Sep 14, 2004 at 13:11 UTC

    Use the quotemeta() function or the "\Q..." construct. Read more about it in perlfunc.

    ihb

    Read argumentation in its context!

      zejames, ihb that worked like a treat. Just what I was looking for.

      Many Thanks

      Steve
Re: using grep with multiple "+"
by qumsieh (Scribe) on Sep 14, 2004 at 16:10 UTC
    Using quotemeta() or \Q..\E as suggested by others is the correct thing to do.

    The reason your regexp was failing was the existence of too many forward slashes. Either use a different delimeter, or escape your forward slashes in your pattern:

    grep m|c:/apps/c\+\+/application| => 'c:/apps/c++/application/myfile.cpp'; grep /c:\/apps\/c\+\+\/application/ => 'c:/apps/c++/application/myfile.cpp';
Re: using grep with multiple "+"
by Anonymous Monk on Sep 14, 2004 at 13:05 UTC
    Note for the line grep {/c:/apps/c\+\+/application/} c:/apps/c++/application/myfile.cpp

    It should read grep {/c:/apps/c\+\+/application/} c:/apps/c\+\+/application/myfile.cpp