我有perl脚本从我的处理中排除几条路径。
现在我想在排除路径中添加一个新文件夹(/foo/
),除了文件名Hello
我知道我们可以使用关键字next
来跳过循环,但是如何只针对特定文件夹下的一个文件实现它呢?
文件夹/foo/
可以放在任何目录中,例如abc/foo/def/
或hij/klm/foo/
use strict;
use warnings;
my @excludepaths = (
"abc/def/",
"hij/klm/",
);
foreach (@excludepaths)
{
if (SOME_TEST_CONDITION) # exclude filename "Hello" under "Foo" folder
{
# move on to the next loop element
next;
}
# more code here ...
}
答案 0 :(得分:1)
诀窍是 - 创建一个正则表达式,并使用|
创建一个或条件。
所以使用你的:
my @excludepaths = (
"abc/def/",
"hij/klm/",
);
将其转换为正则表达式:
my $regex = join ( "|", map { quotemeta } @excludepaths );
$regex = qr/($regex)/;
然后你应该能够做到
next if m/$regex/;
例如:
my @excludepaths = (
"abc/def/",
"hij/klm/",
);
my $regex = join ( "|", @excludepaths );
$regex = qr/($regex)/;
for ( "abc/def/ghk", "abf/de/cg", "abf/hij/klm/ghf", "fish/bat/mix" ) {
next if m/$regex/;
print;
print "\n";
}
如果你这样做,你可以添加任何你喜欢的模式到你的排除'只需将其添加到列表中即可。
所以你可以添加/foo/.*/Hello$
并且它会跳过匹配:
/some/path/to/foo/and/more/Hello
因为正则表达式路径是子串匹配。
编辑:根据您的评论:
my @excludepaths = ( "abc/def/", "hij/klm/", "/foo/", );
my $regex = join( "|", @excludepaths );
$regex = qr/($regex)/;
my $include_regex = qr,/foo/.*\bHELLO$,;
for (
"abc/def/ghk", "abf/de/cg",
"abf/hij/klm/ghf", "fish/bat/mix",
"/path/with/foo/not/HELLO", "/path/with/foo/",
"/path/with/foo/HELLO"
)
{
next if ( m/$regex/ and not m/$include_regex/ );
print;
print "\n";
}
我们明确排除包含/foo/
但覆盖$include_regex
的内容,以便/path/with/foo/not/HELLO
仍然通过文件管理器。