我正在寻找一个Perl代码段100,以将C标头中包含的数字打印到终端。
#ifndef VERSIONS_H
#define VERSIONS_H
#define __SOFTWARE_REVISION__ 100
#endif
Run Code Online (Sandbox Code Playgroud)
我可以提取#define行,但要提取数量。
#!perl -w
use warnings;
use strict;
my $line;
my $file = shift @ARGV;
open my $fh, "<", $file or die $!;
while (<$fh>) {
print if /__SOFTWARE_REVISION__/;
}
close ($fh);
Run Code Online (Sandbox Code Playgroud)
正则表达式匹配包含该文字短语的任何行,而不仅限于定义它的地方。您需要更精确地指定行,并捕获所需的数字。
该代码还将继续循环遍历该文件。
还有一些调整
use warnings;
use strict;
use feature qw(say);
my $file = shift @ARGV;
die "Usage: $0 filename\n" if not $file or not -f $file;
open my $fh, '<', $file or die "Can't open $file: $!";
while (<$fh>) {
if (/^\s*#\s*define\s+__SOFTWARE_REVISION__\s+([0-9]+)/) {
say "Software revision: $1";
last;
}
}
close $fh;
Run Code Online (Sandbox Code Playgroud)
如果软件版本可以不是整数,则替换[0-9]+为\S+。
我建议在手边参考perlre的情况下完成perlretut教程。
我认为Perl程序中会出现这种需求(而不是Perl是为此选择的工具)。
不过,请注意,有其他的,更系统,方法来检索使用编译器该信息(见注释gcc的罗杰斯国际商品指数为例)。
尽管最好在Perl脚本中使用Perl而不是直接使用系统,但这种情况可能是例外之一:最好使用外部命令而不是解析源文件,这是众所周知的棘手的任务。