Result:use strict; my $sql = <<'--SQL--'; select case when a=b then 'c' else 'd' end "tough_one", e as "even tougher" from mytable --SQL-- use HOP::Lexer 'make_lexer'; my @sql = $sql; my $lexer = make_lexer( sub { shift @sql }, # iterator [ DQWORD => qr/"\w+"/ ], [ DQUOTED => qr/"[^"]+"/ ], [ QUOTED => qr/'[^']*'/ ], [ KEYWORD => qr/\b(?:SELECT|FROM|AS|CASE|WHEN|END)\b/i ], [ WORD => qr/\w+/i ], [ COMMA => qr/,/ ], [ SPACE => qr/\s+/, sub {} ], ); # parse my @out; push @out, $_ while $_ = $lexer->(); # Data::Dump the output (elaborated in order to produce compact result +s) use Data::Dumper; $Data::Dumper::Indent = 0; $Data::Dumper::Terse = 1; ($\, $,) = ("\n", ",\n"); print map { Dumper $_ } @out;
['KEYWORD','select'], ['KEYWORD','case'], ['KEYWORD','when'], ['WORD','a'], '=', ['WORD','b'], ['WORD','then'], ['QUOTED','\'c\''], ['WORD','else'], ['QUOTED','\'d\''], ['KEYWORD','end'], ['DQWORD','"tough_one"'], ['COMMA',','], ['WORD','e'], ['KEYWORD','as'], ['DQUOTED','"even tougher"'], ['KEYWORD','from'], ['WORD','mytable']
As to your rule of thumb, it's not always feasable, especially with possibly overlapping matches, for example in Perl, a string can contain a "#" symbol, and a comment can contain quotes. So, which to match first, the comment or the string?
In reply to Re^2: HOP::Lexer not doing what I expected
by bart
in thread HOP::Lexer not doing what I expected
by bart
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |