如何使用 perl6 正则表达式元语法<foo regex>?



在perl6语法中,正如这里所解释的(注意,设计文档不能保证在实现完成时是最新的(,如果左尖括号后跟一个标识符,那么构造是对子规则、方法或函数的调用。

如果标识符后面的字符是左括号,则它是对方法或函数的调用,例如:<foo('bar')>。 正如页面下方进一步解释的那样,如果标识符后的第一个字符是一个空格,那么直到结束角度的其余字符串将被解释为该方法的正则表达式参数 - 引用:

<foo bar>

或多或少等同于

<foo(/bar/)>

使用此功能的正确方法是什么? 就我而言,我正在解析面向行的数据,并且我正在尝试声明一个规则,该规则将引发对正在解析的当前行的单独搜索:

#!/usr/bin/env perl6
# use Grammar::Tracer ;
grammar G {
my $SOLpos = -1 ;   # Start-of-line pos
regex TOP {  <line>+  }
method SOLscan($regex) {
# Start a new cursor
my $cur = self."!cursor_start_cur"() ;
# Set pos and from to start of the current line
$cur.from($SOLpos) ;
$cur.pos($SOLpos) ;
# Run the given regex on the cursor
$cur = $regex($cur) ;
# If pos is >= 0, we found what we were looking for
if $cur.pos >= 0 {
$cur."!cursor_pass"(self.pos, 'SOLscan')
}
self
}
token line {
{ $SOLpos = self.pos ; say '$SOLpos = ' ~ $SOLpos }
[
|| <word> <ws> 'two' { say 'matched two' }  <SOLscan w+> <ws> <word>
|| <word>+ %% <ws>    { say 'matched words' }
]
n
}
token word  {  S+  }
token ws    {  h+  }
}
my $mo = G.subparse: q:to/END/ ;
hello world
one two three
END

实际上,此代码生成:

$ ./h.pl
$SOLpos = 0
matched words
$SOLpos = 12
matched two
Too many positionals passed; expected 1 argument but got 2
in method SOLscan at ./h.pl line 14
in regex line at ./h.pl line 32
in regex TOP at ./h.pl line 7
in block <unit> at ./h.pl line 41
$

14号线是$cur.from($SOLpos)。 如果注释掉,第 15 行会产生相同的错误。 看起来好像 .pos 和 .from 是只读的...(也许:-(

知道正确的咒语是什么吗? 请注意,任何建议的解决方案都可能与我在这里所做的相去甚远 - 我真正想做的是了解应该如何使用该机制。

它似乎不在烘焙的相应目录中,因此恐怕会使其成为"尚未实现"的功能。

最新更新