我从.C文件中获取函数定义大小,并且我在文本文件中列出了所有函数定义名称
CODE
open(FILE, "< file.c") or die $!; #source file
my @lines = <FILE>;
close(FILE);
open(FILE2, "> file_function_size.txt") or die $!;
open(FILE1, "< functions.txt") or die $!; #contains list of function names
chomp( my @functions = <FILE1> );
close(FILE1);
my $match_function = qr/\b(@{[ join '|', map quotemeta, sort { length($b) <=> length($a) } @functions ]})\([^;]+$/;
my %function_size;
my $function = '';
for my $source_line (@lines) {
if ( $source_line =~ $match_function ) {
$function = $1;
$function_size{$function} = 0;
}
elsif ( $source_line =~ /^}/ ) {
$function = '';
}
# ignore first {
elsif ( $function && ( $source_line !~ /^{/ || $function_size{$function} ) ) {
++$function_size{$function};
}
}
for my $function (@functions) {
if ( exists $function_size{$function} ) {
print FILE2 "Function $function has $function_size{$function} lines.\n";
}
}
输出我是
Function ChainCtrlBuildChain has 63 lines.
Function ChainCtrlDumpChain has 22 lines.
Function ChainCtrlExit has 6 lines.
Function ChainCtrlGetBitStreamChan has 36 lines.
我想根据其大小对其进行排序
Function ChainCtrlExit has 6 lines.
Function ChainCtrlDumpChain has 22 lines.
Function ChainCtrlGetBitStreamChan has 36 lines.
Function ChainCtrlBuildChain has 63 lines.
答案 0 :(得分:2)
您可以使用这样的特殊功能:
sub by_size {
$a =~ /Function \s+ has (\d+\) lines./;
my $a_lines = $1;
$b =~ /Function \s+ has (\d+\) lines./;
my $b_lines = $1;
return $a_lines <=> $b_lines;
}
@sorted_output = sort by_size @output;
这假设@output
包含格式的字符串:
Function ChainCtrlBuildChain has 63 lines.
Function ChainCtrlDumpChain has 22 lines.
Function ChainCtrlExit has 6 lines.
Function ChainCtrlGetBitStreamChan has 36 lines.
此行告诉sort
使用by_size
函数进行排序:
@sorted_output = sort by_size @output;
by_size
函数有2个输入:名为$a
和$b
的全局变量。这些是sort
传递给它的。
此函数处理$a
和$b
并返回1
,0
或-1
的值,意思是:
-1
- &gt; $a
来自$b
0
- &gt;出于此排序的目的,$a
等于$b
。1
- &gt; $a
来自$b
在这种特定情况下,by_size
通过从字符串$a
和$b
中提取行数来确定顺序。
答案 1 :(得分:2)
尝试按以下步骤更改打印循环
foreach my $function (sort {$function_size{$a} <=> $function_size{$b}} keys %function_size) {
print FILE2 "Function $function has $function_size{$function} lines.\n";
}
它将根据其值(即大小)对%function_size的键进行数字排序。