2012-01-12 52 views
0

我用模塊解析:: RecDescent的
,並嘗試建立語法趕上perl的子名 爲什麼在我的代碼 https://gist.github.com/1595532解析:: RecDescent的解析子名

不行伽馬 get_sub: NOWORD TEST NOWORD 'test1 $'?

on'> test1 $'? (variabble $ perl_code1)

use Modern::Perl; 
use Parse::RecDescent; 

my $perl_code1 = q{my >test1$ string3 = $object->oldSub(6,7);}; 
my $perl_code2 = q{test1$ string3 = $object->oldSub(6,7);}; 
my $perl_code3 = q{my test1$ string3 = $object->oldSub(6,7);}; 
my @perl_lines = ($perl_code1, $perl_code2, $perl_code3); 
my $var   = 'test1'; 
my $sub_grammar = q{ 

    get_sub: 
      NOWORD TEST NOWORD 
       {print $item[2]}  
      |TEST NOWORD 
       {print $item[1]}  

    get_sub2: 
      WORD TEST NOWORD 
       {print $item[2]}  
      |TEST NOWORD 
       {print $item[1]}  

    WORD: 
     /\w+/  
    NOWORD: 
     /\W+/    
    TEST: 
     /} . $var . q{/ 
    }; 
my $sub_parse = new Parse::RecDescent($sub_grammar); 
say 'example1:'; 

for my $string1 (@perl_lines) { 
    say "Valid sub:$string1\n" if $sub_parse->get_sub($string1); 
} 

say 'example2:'; 
for my $string2 (@perl_lines) { 
    say " Valid sub:$string2\n" if $sub_parse->get_sub2($string2); 
} 
+6

如果您嘗試解析Perl代碼,則需要[PPI](http://search.cpan.org/perldoc?PPI),而不是Parse: :RecDescent的。 – cjm 2012-01-12 09:47:52

回答

2

$perl_code1開始用繩子my,這是不被規則匹配。您需要在文法中使用以下內容:

get_sub: 
     WORD NOWORD TEST NOWORD 
      ...