1

对于找到的每个幻数,我必须使用“找到幻数”消息将输出作为行号提供

我正在解析一个 .C 文件。

幻数基本上是

if(list == 5)          // here 5 is magic number

for(int i = 0; i<6; i++)        //here 6 is magic number

我的代码

use strict;
use warnings;
my $input = $ARGV[0];
open(FILE, $input) or die $!;                                          
my @lines = <FILE>;
my $count = 0; 

foreach(@lines){
     $count++;
 if($_ =~ 'for\('){                       # I want to check within for( )
        if($_ =~ '#####'){                  # how do the check for numbers
           print "magic number found at line:".$count;
   }
  }
     elif($_ =~ 'if\('){                       # I want to check within if( )
        if($_ =~ '#####'){                  
           print "magic number found at line:".$count;
  }
 }
}

由于幻数仅存在于 for 循环和 if 循环中,所以我想检查括号内是否存在任何十进制或十六进制值

4

1 回答 1

3

- 再次编辑。这一次的if条件,它首先匹配成对的括号,然后在 . 后面查找一个数字==

我使它更健壮,因为它可以识别多行条件测试。但是,正如其他人所说,这可能仍然无法覆盖 100% 的可能情况。

use 5.14.0;
use warnings;

my $data = join '', <DATA>;

my $if = qr/if \s* ( \( (?: [^()]++ | (?-1) )*+ \) ) /spx; # matching paired parenthesis
my $for = qr/for (\s*\(.*?;.*?) (\d+) \s*? ; /spx; #(\d+) is for the Magic Number

for($data){
    while (/$if/g){
        my $pat = ${^MATCH};
        my $line =()= ${^PREMATCH} =~ /\n/g;
        # assumes a magic number exists only when '==' is present
        if ($pat =~ /(.* == \s* )([0-9a-fA-F.]+)\s*\)/x){
            my $mn = $2;
            my $condition = $1;
            $line += () = $condition =~ /\n/g;
            say "Line ", $line + 1," has magic number $mn";
        }
    }
    while (/$for/g){
        my $mn = $2; #Magic Number
        my $condition = $1; #For counting \n in the MATCH.
        my $line =()= ${^PREMATCH} =~ /\n/g; #Counting \n in the PREMATCH.
        $line += () = $condition =~ /\n/g;
        say "Line ", $line + 1," has magic number $mn";
    }
}


__DATA__
if(list ==
5)          // here 5 is magic number

for(int i = 0; i<6
 ;
i++
)        //here 6 is magic number

if(list ==
8)          // here 8 is magic number

if (IsMirrorSubChainEnable())
{
    err = ChainCtrlSetMirrorSC(pChainCtrl, pNewRouteInfo);
}

ModCallCallbacks((ModT *)pChainCtrl, kDoneVinResetCallback, NULL, 0);

输出:

Line 2 has magic number 5
Line 10 has magic number 8
Line 4 has magic number 6
于 2013-10-23T13:39:16.030 回答