in reply to Perl6: Dynamic Grammars
What's that old adage...? "Ask and ye shall figure it out yourself." :-D
#!/usr/bin/env perl6 use Test; our %sigils = ( bang => '!', at => '@', hash => '#', dollar => '$', percent => '%', caret => '^', and => '&', star => '*', zero => '0', ); our grammar DynGrammar { my $sigil; regex TOP { ^^ (\w+) <?{ $sigil=%sigils{$0} if %sigils{$0}:exists }> \s+ $sigil (.*?) $sigil \n? $$ } } our class DynActions { method TOP($/) { make $1 } } sub dyn(Str $str) { DynGrammar.parse($str, :actions(DynActions)).made } is dyn('bang !one!' ), 'one', 'parse bang!one ok'; is dyn('zero 0one0' ), 'one', 'parse zero0one ok'; isnt dyn('bang @one@' ), 'one', 'isnt bang@one ok'; isnt dyn('BONK !one!' ), 'one', 'isnt BONK!one ok'; nok DynGrammar.parse('bang @one@', :actions(DynActions)), 'nok'; nok DynGrammar.parse('BONK !one!', :actions(DynActions)), 'unk';
The missing piece was to use a Block (in this case, a <?{condition}> assertion) to save off the capture. (I had initially broken out the assignment from the condition, just in case the expression looked Falsey, but thanks to Perl 6, "0" is True! Hallelujah!)
It still might not be the most idiomatic, I don't know; I'm always open to suggestions...
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Perl6: Dynamic Grammars
by stevieb (Canon) on Jun 01, 2016 at 18:51 UTC | |
by bduggan (Pilgrim) on Jun 06, 2016 at 00:19 UTC | |
|
Re^2: Perl6: Dynamic Grammars
by Anonymous Monk on Jun 07, 2016 at 13:01 UTC | |
by OneTrueDabe (Acolyte) on Jun 10, 2016 at 03:30 UTC | |
by Anonymous Monk on Jun 13, 2016 at 22:58 UTC | |
by raiph (Deacon) on Jun 12, 2016 at 18:16 UTC |