检查魔术数字

时间:2013-10-23 13:24:05

标签: regex perl

对于发现的每个幻数

,我必须将输出作为带有“幻数找到”msg的行号

我正在解析.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循环中,所以我想在括号内检查是否存在十进制或十六进制值

1 个答案:

答案 0 :(得分: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