my $pat = '^x.*d$';
my $dir = '/etc/inet.d';
if ( $dir =~ /$pat/xmsg ) {
print "found ";
}
如何让它成功
答案 0 :(得分:13)
您的模式正在查找以x(^x
)开头并以d(d$
)结尾的字符串。您尝试的路径不匹配,因为它不以x开头。
答案 1 :(得分:4)
太多了'x':
my $pat = '^.*d$';
my $dir = '/etc/inet.d';
if ( $dir =~ /$pat/xmsg ) {
print "found ";
}
答案 2 :(得分:4)
您可以使用YAPE::Regex::Explain来帮助您理解正则表达式:
use strict;
use warnings;
use YAPE::Regex::Explain;
my $re = qr/^x.*d$/xms;
print YAPE::Regex::Explain->new($re)->explain();
__END__
The regular expression:
(?msx-i:^x.*d$)
matches as follows:
NODE EXPLANATION
----------------------------------------------------------------------
(?msx-i: group, but do not capture (with ^ and $
matching start and end of line) (with .
matching \n) (disregarding whitespace and
comments) (case-sensitive):
----------------------------------------------------------------------
^ the beginning of a "line"
----------------------------------------------------------------------
x 'x'
----------------------------------------------------------------------
.* any character (0 or more times (matching
the most amount possible))
----------------------------------------------------------------------
d 'd'
----------------------------------------------------------------------
$ before an optional \n, and the end of a
"line"
----------------------------------------------------------------------
) end of grouping
----------------------------------------------------------------------
此外,在这种情况下,您不需要g
修饰符。该文档包含大量有关正则表达式的信息:perlre
答案 3 :(得分:3)
我的猜测是,您尝试列出名称与正则表达式匹配的/etc/init.d
中的所有文件。
Perl不够聪明,无法确定当您命名字符串变量$dir
时,为其分配现有目录的完整路径名,并对其进行模式匹配,您不打算匹配路径名,
但是针对该目录中的文件名。
解决此问题的一些方法:
perldoc -f glob
perldoc -f readdir
perldoc File::Find
您可能只想使用此功能:
if (glob('/etc/init.d/x*'))
{
warn "found\n";
}