在 perl6 语法中,如所解释的 here (请注意,在实现完成后,不保证设计文档是最新的),如果左尖括号后跟标识符,则构造是对子规则、方法或函数的调用。
如果标识符后面的字符是左括号,则它是对方法或函数的调用,例如:<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 是只读的...(也许:-)
你知道正确的咒语是什么吗? 请注意,任何建议的解决方案都可能与我在这里所做的相距甚远 - 我真正想做的就是了解如何使用该机制。
最佳答案
好像不是in the corresponding directory in roast ,恐怕这将使它成为“尚未实现”的功能。
关于raku - 如何使用 perl6 正则表达式元语法 <foo regex>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50210456/