testing for substrings in perl

Matthew Seaman m.seaman at infracaninophile.co.uk
Sun Oct 5 09:43:26 PDT 2003


On Sun, Oct 05, 2003 at 11:32:11AM -0400, 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.

That's why perl has the \Q...\E metasymbols:

Try:

    $match = qr{^/?\Q$dirname\E/};

See perldoc perlre for details.

	Cheers,

	Matthew
	
-- 
Dr Matthew J Seaman MA, D.Phil.                       26 The Paddocks
                                                      Savill Way
PGP: http://www.infracaninophile.co.uk/pgpkey         Marlow
Tel: +44 1628 476614                                  Bucks., SL7 1TH UK
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 187 bytes
Desc: not available
Url : http://lists.freebsd.org/pipermail/freebsd-hackers/attachments/20031005/dbd6e1e5/attachment.bin


More information about the freebsd-hackers mailing list