2009-06-09 29 views
2

我正在研究一个Parse :: RecDescent语法来读取给定的一组可读的规则,然后吐出一个文件,这对于计算机来说更容易阅读。在Parse :: RecDescent正则表达式中插入变量

其中一个令牌是“关键字”列表;约26个不同的关键字。这些可能会随着时间而改变,并可能被多段代码引用。因此,我想将关键字-y的东西存储在数据文件中并加载它们。

Parse :: RecDescent的一个功能是能够在正则表达式中插入变量,并且我想使用它。

我写了一些代码作为概念证明:

@arr = ("foo", "bar", "frank", "jim"); 


$data = <<SOMEDATA; 
This is some data with the word foo in it 
SOMEDATA 

$arrstr = join("|", @arr); 

if($data =~ /($arrstr)/) 
{ 
    print "Matched $1\n"; 
} 
else 
{ 
    print "Failed to match\n"; 
} 

这工作正常。 当我搬到实现它在我的主程序中,我写道:

{ 
    my $myerror = open(FILE, "data.txt") or die("Failed to open data"); 
    my @data_arr = <FILE>; 
    close FILE; 
    my $dataarrstr = join("|", @data_arr); 

} 
#many rules having nothing to do with the data array are here... 

event : /($dataarrstr)/ 
    { $return = $item[1]; } 
    | 

而在这一点上,我与P收到此错误:: RD:ERROR (line 18): Invalid event: Was expecting /($dataarrstr)/

我不知道为什么。有没有人有任何想法来帮助我在这里?

编辑: 这不是一个范围界定问题 - 我试过了。我也尝试了m {...}语法。

回答

3

在仔细阅读了文档和http://perlmonks.org/?node_id=384098上的一个非常类似的问题之后,我制定了这个解决方案。

event :/\w+/ 
    { 
     $return = ::is_valid_event($item[1]); 
    } 
    | <error> 

语法外 -

#This manages the problem of not being able to interpolate the variable 
#in the grammar action 
sub is_valid_event { 
    my $word = shift @_; 
    if($word =~ /$::data_str/) 
    { 
     return $word; 
    } 
    else 
    { 
     return undef; 
    } 
}