- 论坛徽章:
- 0
|
文本解析的利器:- #!/usr/bin/perl
- use strict; use warnings;
- use Data::Dumper;
- use Parse::RecDescent;
- # define grammar
- my $grammar = <<'EOG';
- start: condition { $return = [ $item[1] ] }
- condition: 'if' expr 'then' condition(s?) 'end' { $return = [ @item[1..5] ] }
- | 'if' expr 'then' code 'end' { $return = [ @item[1..5] ] }
- expr: /\S+/
- code: /\S+/
- EOG
- my $line = 'if a then if b then if c then d end if e then f end end end';
- my $parser = new Parse::RecDescent($grammar)
- or die "Compilation error!\n";
- my $raConds = $parser->start($line);
- print Dumper $raConds;
- exit;
复制代码 result:- $VAR1 = [
- [
- 'if',
- 'a',
- 'then',
- [
- [
- 'if',
- 'b',
- 'then',
- [
- [
- 'if',
- 'c',
- 'then',
- 'd',
- 'end'
- ],
- [
- 'if',
- 'e',
- 'then',
- 'f',
- 'end'
- ]
- ],
- 'end'
- ]
- ],
- 'end'
- ]
- ];
复制代码 |
|