ablog

不器用で落着きのない技術者のメモ

Parse::RecDescent を使ってみる

  • cpanminus をインストールする。
bash-3.2$ git clone git://github.com/miyagawa/cpanminus.git
Cloning into cpanminus...
remote: Counting objects: 3355, done.
remote: Compressing objects: 100% (1284/1284), done.
remote: Total 3355 (delta 1646), reused 3089 (delta 1508)
Receiving objects: 100% (3355/3355), 649.60 KiB | 146 KiB/s, done.
Resolving deltas: 100% (1646/1646), done.
bash-3.2$ cd cpanminus
bash-3.2$ perl Makefile.PL 
Generating bin/cpanm from cpanm
Checking if your kit is complete...
Looks good
Writing Makefile for App::cpanminus
bash-3.2$ make install
cp lib/App/cpanminus/script.pm blib/lib/App/cpanminus/script.pm
cp lib/App/cpanminus.pm blib/lib/App/cpanminus.pm
cp bin/cpanm blib/script/cpanm
/usr/bin/perl.exe -MExtUtils::MY -e 'MY->fixin(shift)' -- blib/script/cpanm
Manifying blib/man1/cpanm.1
Manifying blib/man3/App.cpanminus.3pm
Installing /usr/lib/perl5/site_perl/5.10/App/cpanminus.pm
Installing /usr/lib/perl5/site_perl/5.10/App/cpanminus/script.pm
Installing /usr/share/man/man1/cpanm.1
Installing /usr/share/man/man3/App.cpanminus.3pm
Installing /usr/local/bin/cpanm
Appending installation info to /usr/lib/perl5/5.10/i686-cygwin/perllocal.pod
  • Parse::RecDescent をインストールする。
bash-3.2$ /usr/local/bin/cpanm -f Parse::RecDescent
--> Working on Parse::RecDescent
Fetching http://search.cpan.org/CPAN/authors/id/D/DC/DCONWAY/Parse-RecDescent-1.965001.tar.gz ... OK
Configuring Parse-RecDescent-1.965001 ... OK
Building and testing Parse-RecDescent-1.965001 ... OK
Successfully installed Parse-RecDescent-1.965001
  • recdescent_sample01.pl
#!/usr/bin/env perl
use strict;
use warnings;
use Parse::RecDescent;

my $grammar = q(
	sql : /\"([\w\s]+)\"/
		{ $item[1] =~ /\"([\w\s]+)\"/; $return = $1; }
);

my $parser = Parse::RecDescent->new($grammar);

my $text = <<TEXT;
"SELECT ENAME FROM EMP"
TEXT

print $parser->sql($text) . "\n";

実行してみると、

bash-3.2$ ./recdescent_sample01.pl 
SELECT ENAME FROM EMP

こんな感じ。

参考


追記(2011/01/31):
csourceparser.pl を使ってみた。

bash-3.2$ wget http://search.cpan.org/src/DCONWAY/Parse-RecDescent-1.965001/demo/demo_another_Cgrammar.pl
bash-3.2$ mv demo_another_Cgrammar.pl csourceparser.pl 
bash-3.2$ find ./src -type f -name '*.pc' -print0|xargs -0 -n1 ./csourceparser.pl -f