Skip site navigation (1)Skip section navigation (2)
Date:      Sun, 5 Oct 2003 09:41:10 -0700 (PDT)
From:      =?ISO-8859-1?Q?Mikko_Ty=F6l=E4j=E4rvi?= <mbsd@pacbell.net>
To:        Dan Langille <dan@langille.org>
Cc:        freebsd-hackers@freebsd.org
Subject:   Re: testing for substrings in perl
Message-ID:  <20031005092645.J3248@atlas.home>
In-Reply-To: <20031005111656.R18760@xeon.unixathome.org>
References:  <20031005111656.R18760@xeon.unixathome.org>

next in thread | previous in thread | raw e-mail | index | archive | help
On Sun, 5 Oct 2003, Dan Langille wrote:

> Hi,
>
> I have a perl regex to test if a file resides under a particular
> directory.  The test looks like this:
>
> if ($filename =~ $directory) {
>    # yes, this filename resides under directory
> }
>
> This is working for most cases.  However, it fails is the directory
> contains a +.  For example:
>
> $filename = 'ports/www/privoxy+ipv6/files/patch-src::addrlist.c';
>
> $match = "^/?" . 'ports/www/privoxy+ipv6' . "/";
> if ($filename =~ $match) {
>    print "found\n";
> } else{
>    print "NOT found\n";
> }
>
> Yes, I can escapte the + in the directory name, but then I'd have to test
> for all those special regex characters and escape them too.

Or use quotemeta()...

> I think it might just be easier to do a straight comparison of the first N
> characters of the two strings where N = length of the directory name.
>
> Any suggestions?

...or the \Q operator.  Thus:

   $filename = 'ports/www/privoxy+ipv6/files/patch-src::addrlist.c';

   $dir = 'ports/www/privoxy+ipv6';
   if ($filename =~ m:^/?\Q$dir\E/:) {
      print "found\n";
   } else{
      print "NOT found\n";
   }

   $.02,
   /Mikko



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20031005092645.J3248>