in reply to Re: HOP::Lexer not doing what I expected
in thread HOP::Lexer not doing what I expected

Right, OK, got it. This even seems to work as I want:
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;
Result:
['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?

Replies are listed 'Best First'.
Re^3: HOP::Lexer not doing what I expected
by cmarcelo (Scribe) on Nov 12, 2006 at 00:49 UTC

    Indeed, my rule of thumb isn't that good after all :-(. This snippet illustrate what you said about string vs. comment:

    Here is ambiguous what to do, and both orders give a bad result. If STRING comes first, it finds strings inside comments, and if COMMENT comes first, it finds comments inside string.

    (Well, there's a workaround similar to what the original article used to deal with parenthesis, which involves another parsing phase, but this is a little bit cheating I guess ;-)