2013-10-23 55 views
1

我必須輸出行數爲「找到神奇數字」味精,找到每個神奇數字檢查神奇數字

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

幻數基本上是

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

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

MY CODE

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循環,並且如果循環,所以想的,如果存在任何小數托架內,以檢查或十六進制值

+0

我認爲這是比'regex'檢查要複雜得多。如果每個子句在不同的行中都有'for'?或者是一個名爲'i345'而不是'i'的變量?只說幾個問題。 – Birei

+0

@Birei是真的...... dnt想想那個,然後再做任何其他的方式 –

+6

因此,讓我直截了當地說,你想解析C代碼,但是你從來沒有在你的問題中提過它?也許你應該? – TLP

回答

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 
+0

它工作正常。但正如用戶birei所指出的那樣,如果條件語句是多行的,那麼它會給出慾望輸出 –

+1

@ Ad-vic:我會說這對於尋找一些代碼問題並不是非常有用。如果這就是這樣,那麼請考慮投資回報。這段代碼很簡單,可能會找到你想要的75%。此外,您可能會啓動編輯器並開始修復,並會發現更多。在您的「神奇號碼查找器」中獲得更高的準確性需要時間遠離您的修復。 。 。 –

+0

@ Ad-vic:我編輯了代碼以使它更加健壯。 –