在下面的代码中,我正在检查数组excluded.It中的一个特定变量位置,它可以很好地处理除一个excluded.It之外的所有数组元素。当我提供这个元素作为我的位置时,它的打印“位置不排除”,即使它被排除了。
我如何使我的代码得到这个元素以及排除?
use strict;
use warnings;
my @excluded = (
"xyz/efg/headers/",
"abc/def/libraries/jni-mr.h",
"abc/def/libraries/linux_3.2.60-1+deb7u3.dsc",
);
my $location = "abc/def/libraries/linux_3.2.60-1+deb7u3.dsc";
my $badpath = 0;
foreach (@excluded) {
# -- Check if location is contained in excluded array
if ($location =~ /^$_/) {
$badpath = 1;
print "location is excluded : $location \n";
}
}
if (! $badpath) {
print "location is not excluded : $location \n";
}期望产出:
location is excluded : abc/def/libraries/linux_3.2.60-1+deb7u3.dsc当前产出:
location is not excluded : abc/def/libraries/linux_3.2.60-1+deb7u3.dsc发布于 2015-03-24 14:20:28
使用quotemeta($text)或\Q$text\E (在双引号或正则表达式中)创建与$text值匹配的模式。换句话说,使用
if ($location =~ /^\Q$_\E/)而不是:
if ($location =~ /^$_/)发布于 2015-03-24 14:23:27
+),它是大多数正则表达式(包括Perl)中的一个或多个乘数,但您需要匹配它。^锚点从循环移动到每个单独的regex,这将使代码更加灵活,因为如果您愿意,可以选择不锚定一些排除正则表达式。qr()构造,它允许您预编译正则表达式,并保存在CPU上。grep()的一个很好的选择。use strict;
use warnings;
my @excluded = (
qr(^xyz/efg/headers/),
qr(^abc/def/libraries/jni-mr\.h),
qr(^abc/def/libraries/linux_3\.2\.60-1\+deb7u3\.dsc),
);
my $location = 'abc/def/libraries/linux_3.2.60-1+deb7u3.dsc';
# -- Check if location is contained in excluded array
my $badpath = scalar(grep($location =~ $_, @excluded )) >= 1 ? 1 : 0;
if ($badpath) {
print "location is excluded : $location \n";
} else {
print "location is not excluded : $location \n";
}https://stackoverflow.com/questions/29234874
复制相似问题