我想使用Perl对文本文件执行“搜索和替换”,并在替换完成后将每个匹配结果(作为元素)存储到数组中。我尝试了这个:
my $txt = "
this is a statement //this is comment
//this is a line of comment
more statements //more comments
";
## foreach or while
while ($txt =~ s/(\/\/.*?\n)/foo/gs) {
if(defined $1) {
push (@comments, $1);
}
}
foreach (0..$#comments) {
print "\@comments[$_]= @comments[$_]";
}
====>但是结果只给了我:
@comments[0]= //more comments
而我期望的是:
@comments[0]= //this is comment
@comments[1]= //this is a line of comment
@comments[2]= //more comments
关于这个问题有什么提示吗?提前谢谢&3q〜
您可以使用e修饰符在替换内部执行代码(请参见perlretut):
my $txt = "
this is a statement //this is comment
//this is a line of comment
more statements //more comments
";
my @comments;
$txt =~ s{(//.*\n)} {push(@comments, $1);"foo"}eg;
print $_ foreach (@comments);
其他方法:由于您正在寻找内联注释,因此也可以逐行处理带有循环且没有g修饰符的代码。
笔记:
\n
从模式中删除。//
可以包含在字符串中,因此更安全的方法是使用适当的解析器。本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句