听起来像是Parse::RecDescent 的案例:
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;
语法,英文:
整个事情都是一个表达。表达式是一个操作数,后跟零个或多个二元运算符及其操作数。每个操作数都是带括号的表达式,“!”后跟一个操作数或一个单词(例如cond1)。
生成树中的每个节点都采用以下形式之一:
-
cond1 - 一个条件
-
{ 'op' => '!', 'value' => 'node' } - !应用于另一个节点
-
{ 'lvalue' => 'node', 'operations' => [ one or more of: { 'op' => 'binop', 'rvalue' => 'node' } ] } - 一系列一个或多个操作,代表节点 binop 节点 binop 节点 ...
我没有将一系列二元运算(例如((cond1) || (cond2) || (cond3)))分解成二叉树,因为您没有提供有关优先级或关联性的信息。
您的示例的输出是:
$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'
}
]
}
}
]
};