首先,如果你要 slurp 文件,你应该使用File::Slurp。然后你可以这样做:
my $contents = read_file $file;
read_file 会因错误而嘶哑。
其次,[^typename] 不仅排除字符串 'typename',还排除包含任何这些字符的任何字符串。除此之外,对我来说,您使用的模式是否会始终匹配您希望它匹配的内容对我来说并不明显,但我现在无法对此发表评论。
最后,要一一获取文件中的所有匹配项,请在循环中使用 g 修饰符:
my $source = '3 5 7';
while ( $source =~ /([0-9])/g ) {
print "$1\n";
}
既然我有机会查看您的模式,我仍然不确定如何制作 [^typename],但这里有一个示例程序,它捕获了尖括号之间的部分(因为这似乎是唯一的您在上面捕获的东西):
use strict;
use warnings;
use File::Slurp;
my $pattern = qr{
^
\w+
<\s*((?:\w+(?:,\s*)?)+)\s*>
\s*
\w+\s*;
}mx;
my $source = read_file \*DATA;
while ( $source =~ /$pattern/g ) {
my $match = $1;
$match =~ s/\s+/ /g;
print "$match\n";
}
__DATA__
CMyClass<int> myClassInstance;
CMyClass2<
int,
int
> myClass2Instacen;
C:\Temp> t.pl
int
int, int
现在,我怀疑您更喜欢以下内容:
my $pattern = qr{
^
(
\w+
<\s*(?:\w+(?:,\s*)?)+\s*>
\s*
\w+
)
\s*;
}mx;
产生:
C:\Temp> t.pl
CMyClass<int> myClassInstance
CMyClass2< int, int > myClass2Instacen