From owner-freebsd-hackers@FreeBSD.ORG Sun Oct 5 09:41:12 2003 Return-Path: Delivered-To: freebsd-hackers@freebsd.org Received: from mx1.FreeBSD.org (mx1.freebsd.org [216.136.204.125]) by hub.freebsd.org (Postfix) with ESMTP id DAF7E16A4C1 for ; Sun, 5 Oct 2003 09:41:12 -0700 (PDT) Received: from mta7.pltn13.pbi.net (mta7.pltn13.pbi.net [64.164.98.8]) by mx1.FreeBSD.org (Postfix) with ESMTP id B56C243FE3 for ; Sun, 5 Oct 2003 09:41:11 -0700 (PDT) (envelope-from mbsd@pacbell.net) Received: from atlas (adsl-64-165-199-197.dsl.snfc21.pacbell.net [64.165.199.197]) by mta7.pltn13.pbi.net (8.12.9/8.12.3) with ESMTP id h95GfB1S005450; Sun, 5 Oct 2003 09:41:11 -0700 (PDT) Date: Sun, 5 Oct 2003 09:41:10 -0700 (PDT) From: =?ISO-8859-1?Q?Mikko_Ty=F6l=E4j=E4rvi?= X-X-Sender: mikko@atlas.home To: Dan Langille In-Reply-To: <20031005111656.R18760@xeon.unixathome.org> Message-ID: <20031005092645.J3248@atlas.home> References: <20031005111656.R18760@xeon.unixathome.org> MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII cc: freebsd-hackers@freebsd.org Subject: Re: testing for substrings in perl X-BeenThere: freebsd-hackers@freebsd.org X-Mailman-Version: 2.1.1 Precedence: list List-Id: Technical Discussions relating to FreeBSD List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Sun, 05 Oct 2003 16:41:13 -0000 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