我有一个 Perl 程序:
- 读取用 C 编写的 SRC 文件
- 使用 SRC 文件中的正则表达式匹配来查找特定格式的数据以用作目标文件名
- 打开新的目标文件
- 执行另一个正则表达式匹配以查找包含关键字 abcd 的所有 C 风格注释 /* */。注意:这些注释可以是 1 行或多于 1 行,因此正则表达式会查找第一个 /*,然后查找关键字 abcd,然后在遇到结束符之前查找任意数量的文本和空格 */
- 将正则表达式匹配写入目标文件
#!/usr/bin/perl
use warnings;
use strict;
my $src = 'D:\\Scripts\\sample.c';
my $fileName;
# open source file for reading
open(SRC_FH,'<',$src) or die $!;
while(my $row = <SRC_FH>){
if ($row =~ /([0-9]{2}\.[0-9]{2}\.[0-9]{3}\.[a-z,0-9]{2}|[0-9]{2}\.[0-9]{2}\.[0-9]{3}\.[a-z,0-9]{3})/){
$fileName = $1;
}
}
my $des = "D:\\Scripts\\" . $fileName . ".txt";
# open destination file for writing
open(DES_FH,'>',$des) or die $!;
print("copying content from $src to $des\n");
seek SRC_FH, 0, 0;
while(my $row = <SRC_FH>){
if ($row =~ /(\/\*.*abcd.[\s\S]*?\*\/)/){
print DES_FH "$1\n";
}
}
# always close the filehandles
close(SRC_FH);
close(DES_FH);
print "File content copied successfully!\n";
我的问题是,我认为由于 perl 代码的执行方式,尽管正则表达式是正确的,但我的目标文件仅写入了 1 行注释。任何超过 1 行的 C 风格注释都不会写入目标文件。我的第二个 if 语句中缺少什么?
我在这里检查了我的第二个 if 语句正则表达式https://regexr.com/ https://regexr.com/它的工作原理是捕获多行 C 风格注释以及也包含关键字 abcd 的单行注释。
所以我尝试了 zdim 下面的第一个建议。这是我使用的:
#!/usr/bin/perl
use warnings;
use strict;
my $src = 'D:\\Scripts\\sample.c';
my $fileName;
my @comments;
# open source file for reading
open(SRC_FH,'<',$src) or die $!;
while(my $row = <SRC_FH>){
if ($row =~ /([0-9]{2}\.[0-9]{2}\.[0-9]{3}\.[a-z,0-9]{2}|[0-9]{2}\.[0-9]{2}\.[0-9]{3}\.[a-z,0-9]{3})/){
$fileName = $1;
}
}
my $des = "D:\\Scripts\\" . $fileName . ".txt";
# open destination file for writing
open(DES_FH,'>',$des) or die $!;
print("copying content from $src to $des\n");
#seek SRC_FH, 0, 0;
my $content = do {
#read whole file at once
local $/;
open (SRC_FH,'<', $src) or die $!;
<SRC_FH>;
};
#if($content =~ /(\/\*.*abcd.[\s\S]*?\*\/)/sg){
# my @comments = $content;
# }
my @comments = $content =~ /(\/\*.*abcd.[\s\S]*?\*\/)/sg;
foreach (@comments){
print DES_FH "$1\n";
}
#while(my $row = <SRC_FH>){
# if ($row =~ /(\/\*.*abcd.[\s\S]*?\*\/)/){
# print DES_FH "$1\n";
# }
#}
# always close the filehandles
close(SRC_FH);
close(DES_FH);
print "File content copied successfully!\n";
结果是将sample.c 中的所有内容复制到目标文件。完整的 1:1 副本。我希望从 C 文件中提取所有单行和多行注释。
示例1:
/* A B C D */
示例2:
/* 一些文本
* 更多评论
abcd 和一些更多评论 */
最终解决方案
#!/usr/bin/perl
use warnings;
use strict;
my $src = 'D:\\Scripts\\sample.c';
my $fileName;
# open source file for reading
open(SRC_FH,'<',$src) or die $!;
while(my $row = <SRC_FH>){
if ($row =~ /([0-9]{2}\.[0-9]{2}\.[0-9]{3}\.[a-z,0-9]{2}|[0-9]{2}\.[0-9]{2}\.[0-9]{3}\.[a-z,0-9]{3})/){
$fileName = $1;
}
}
my $des = "D:\\Scripts\\" . $fileName . ".txt";
# open destination file for writing
open(DES_FH,'>',$des) or die $!;
print("copying content from $src to $des\n");
seek SRC_FH, 0, 0;
my $content = do{local $/; <SRC_FH>};
my @comments = $content =~ /(\/\*.*abcd.[\s\S]*?\*\/)/g;
for(@comments){
print DES_FH "$_\n";
}
# always close the filehandles
close(SRC_FH);
close(DES_FH);
print "File content copied successfully!\n";