testing for substrings in perl
Mikko Työläjärvi
mbsd at pacbell.net
Sun Oct 5 09:41:13 PDT 2003
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
More information about the freebsd-hackers
mailing list