- 论坛徽章:
- 46
|
本帖最后由 zhlong8 于 2010-10-24 00:02 编辑
package T- package T;
- use 5.012;
- use warnings;
- sub new {
- my($class, $parent) = @_;
- bless {
- current => [],
- parent => $parent
- }, $class;
- }
- sub dec {
- my $self = shift;
- push @{$self->{parent}{current}}, $self->{current};
- $self->{parent};
- }
- sub add {
- my($self, $val) = @_;
- push @{$self->{current}}, $val;
- }
- sub top {
- bless {current => [], parent=> []}, shift;
- }
- 1;
复制代码 实现- use 5.012;
- use warnings;
- use T;
- use Data::Dumper;
- use Regexp::Common;
- sub parse {
- my $tree = T->top;
- for (@_) {
- given ($_) {
- when ('(') {$tree = T->new($tree)}
- when (')') {$tree = $tree->dec;}
- default {$tree->add($_);}
- }
- }
- say Dumper $tree;
- }
- sub tokenize { #功能非常有限
- my $str = shift;
- say "got $str";
- my @all;
- while ($str =~ /\G\s*(\(|\)|$RE{num}{real}|$RE{num}{int}|\w+|[+\-*\/])\s*/g) {
- push @all, $1;
- }
- say "return @all";
- @all;
- }
- #(define a (+ 343 (* 3323 a)))
- parse '(', 'define', 'a', '(', '+', '343', '(', '*', '3323', 'a', ')', ')', ')';
- #或者
- parse tokenize '(define a (+ 343 (* 3323 a)))'
复制代码 输出- $VAR1 = bless( {
- 'parent' => [],
- 'current' => [
- [
- 'define',
- 'a',
- [
- '+',
- '343',
- [
- '*',
- '3323',
- 'a'
- ]
- ]
- ]
- ]
- }, 'T' );
复制代码 有个Parse::RecDescent 模块,不过我不会用
还有 Regexp::Common::balanced |
|