在Parse :: RecDescent正则表达式中插入变量

时间:2009-06-09 17:27:38

标签: perl 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 {...}语法。

1 个答案:

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