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...
In reply to Re: Perl6: Dynamic Grammars
by OneTrueDabe
in thread Perl6: Dynamic Grammars
by OneTrueDabe
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |