perl6 grammars

perl6 got out and it looks nice and how wouldn’t it it’s perl.

there ain’t much examples tuts online so here is one.

What is so neat about this new perl is that grammars are first class citizens yay \o/

now you can just make your grammar like so

use v6;

grammar X {
token letter { \w }
token word { + }
token quantifier { '*'|'?' }
token orop { '|' }
rule quantified { | }
rule unit { | }
rule group { ['('][')'] }
rule unitgroup {+ }
rule unitgroups {|}
rule TOP { }
}

so you defined the grammar now what 😀

well we can have actions fired when each rule is matched

class A {
has $.field; # `$.field` is immutable.
has $.word;
has @.words is rw; 

method orop($n) {
say "orop $n";
}
method letter($n) {
say "letter $n";
}
method word($word) {
say "word $word";
push @!words, $word
}
method quantifier($n) {
say "quantifier $n";
}
method unitgroup($n) {
say "unitgroup $n ";
}
method unitgroups($n) {
say "unitgroups $n ";
}
method unit($n) {
say "unit $n ";
}
method group($n) {
say "group $n";
}
method regexp ($n) {
say "regexp $n";
}
method TOP ($n) {
say "top $n";
}
};

that creates class with words array that will get a word pushed in it as it is matched

now how you use it all

this will create instance of class with our actions and pass it to grammar so those actions get fired
they are matched by name

my $string ='(St|ring)?asd|asd|asdasd';
my $string2 = "asd(String)?";
my $a = A.new;
try X.parse($string, :actions($a));

if $! {
say "Parse failed: ", $!.message;

}
elsif $/ {
say $();

say "words in a exp = " , $a.words.join(",")
}
else {
say "Parse failed.";
}

this github page for the grammars is good tutorial
it shows also how to inline actions into grammars like in the middle of the rule

grammar Foo {
regex foo { blah blah { say "hi" } blah blah }
}

call method on grammar

grammar Foo {
method m{}
rule that{
<.m>
}
regex foo { blah blah { say "hi" } blah blah }
}

access group from lambda

grammar Foo {
rule foo { (\d+) { say "hi $0" } }
}

fire an action method from lambda

grammar Foo {
regex foo { blah blah { say "hi"; $*ACTIONS.thisismethodinactionobjectfromabove } blah blah }
}

also this

grammar Foo {
rule x{

{
$*ACTIONS.aftergroup($);
}
}

also

  '=' 

from here

Leave a Comment