DVK*_*DVK 8 perl parsing state-machine
在解析文本时,我经常需要按照以下代码的通用形式实现迷你状态机.
是否有CPAN模块被认为是"最佳实践"并且非常适合以简单而优雅的方式实现这样的状态机逻辑?
我希望解决方案不那么复杂Parse::RecDescent
但如果不存在并且Parse::RecDescent
比我想象的更容易应用于这个问题,我非常愿意考虑它而不是像我到目前为止一样滚动自己.
示例通用解析代码:
my $state = 1;
while (my $token = get_next_token()) { # Usually next line
if ($state == 1) {
do_state1_processing();
if (token_matches_transition_1_to_2($token)) {
do_state_1_to_2_transition_processing();
$state == 2;
next;
} elsif (token_matches_transition_1_to_4($token)) {
do_state_1_to_4_transition_processing();
$state == 4;
next;
} else {
do_state1_continuation();
next;
}
} elsif ($state == 5) {
do_state5_processing();
if (token_matches_transition_5_to_6($token)) {
do_state_5_to_6_transition_processing();
$state == 6;
next;
} elsif (token_matches_transition_5_to_4($token)) {
do_state_5_to_4_transition_processing();
$state == 4;
next;
} else {
do_state5_continuation();
next;
}
} else {
}
}
Run Code Online (Sandbox Code Playgroud)
看看这个简单的计算器就知道了。
my $grammar = Marpa::XS::Grammar->new(
{ start => 'Expression',
actions => 'My_Actions',
default_action => 'first_arg',
rules => [
{ lhs => 'Expression', rhs => [qw'Term'] },
{ lhs => 'Term', rhs => [qw'Factor'] },
{ lhs => 'Factor', rhs => [qw'Number'] },
{ lhs => 'Term', rhs => [qw'Term Add Term'], action => 'do_add' },
{ lhs => 'Factor',
rhs => [qw'Factor Multiply Factor'],
action => 'do_multiply'
},
],
}
);
Run Code Online (Sandbox Code Playgroud)
您必须自己实现标记生成器。
归档时间: |
|
查看次数: |
1196 次 |
最近记录: |