在Perl中解析逻辑表达式并将其转换为树
我有一个复杂的逻辑表达式,如下所示:在Perl中解析逻辑表达式并将其转换为树,perl,parsing,logic,Perl,Parsing,Logic,我有一个复杂的逻辑表达式,如下所示: ((((!((cond1) || (cond2) || (cond3)) && (cond4))) && (cond5)) <= (((cond6) || (cond7) || (cond8)) || (cond9))) ((!((cond1)| |(cond2)| |(cond3))&&&&(cond4))&&&(cond5))听起来像是一个例子: 这些表达式是Perl还是来自另一种语言?是不是只有一次代码清理?它不
((((!((cond1) || (cond2) || (cond3)) && (cond4))) && (cond5)) <= (((cond6) || (cond7) || (cond8)) || (cond9)))
((!((cond1)| |(cond2)| |(cond3))&&&&(cond4))&&&(cond5))听起来像是一个例子:
这些表达式是Perl还是来自另一种语言?是不是只有一次代码清理?它不是在Perl,它是.VA文件,我不确定它是什么语言。我想写一个Perl脚本来解析它。YSIT是正确的,你应该使用正式的语法来解决你的问题。你也应该考虑,这是解析的继承者::cDescent,如果您使用的是Perl 5.10或更高版本。请您解释一下它是做什么的,它以什么格式返回结果。我需要处理数据,但我不知道如何访问它。@Ilya Melamed:我希望它是不言自明的,但我添加了一个解释尝试。
use strict;
use warnings;
use Parse::RecDescent;
my $text = '((((!((cond1) || (cond2) || (cond3)) && (cond4))) && (cond5)) <= (((cond6) || (cond7) || (cond8)) || (cond9)))';
#$::RD_TRACE=1;
my $grammar = q{
startrule: expr
expr: operand operation(s?)
{ $return = @{$item[2]} ? { 'operations' => $item[2], 'lvalue' => $item[1] } : $item[1] }
operation: /\|\||&&|<=/ operand
{ $return = { 'op' => $item[1], 'rvalue' => $item[2] } }
operand: '(' expr ')'
{ $return = $item[2] }
operand: '!' operand
{ $return = { 'op' => '!', 'value' => $item[2] } }
operand: /\w+/
};
my $parser = Parse::RecDescent->new($grammar);
my $result = $parser->startrule($text) or die "Couldn't parse!\n";
use Data::Dumper;
$Data::Dumper::Indent = 1;
$Data::Dumper::Sortkeys = 1;
print Dumper $result;
$VAR1 = {
'lvalue' => {
'lvalue' => {
'lvalue' => {
'op' => '!',
'value' => {
'lvalue' => 'cond1',
'operations' => [
{
'op' => '||',
'rvalue' => 'cond2'
},
{
'op' => '||',
'rvalue' => 'cond3'
}
]
}
},
'operations' => [
{
'op' => '&&',
'rvalue' => 'cond4'
}
]
},
'operations' => [
{
'op' => '&&',
'rvalue' => 'cond5'
}
]
},
'operations' => [
{
'op' => '<=',
'rvalue' => {
'lvalue' => {
'lvalue' => 'cond6',
'operations' => [
{
'op' => '||',
'rvalue' => 'cond7'
},
{
'op' => '||',
'rvalue' => 'cond8'
}
]
},
'operations' => [
{
'op' => '||',
'rvalue' => 'cond9'
}
]
}
}
]
};