在 Perl 6 中将正则表达式作为参数传递 [英] Passing regexes as arguments in Perl 6
问题描述
这个问题的延续,可能还有一个更奇怪的问题.
A continuation of this question, and probably an even more weird one.
我可以例如使用 sub
连接两个 regex
?(当然,我明白,如何用 regex
做到这一点)
Can I e.g. concatenate two regexes
using a sub
?
(Of course, I understand, how to do it with a regex
)
下面的代码是完全错误的,但我希望它能解释我想做什么:
The following code is totally wrong, but I hope it can explain what I want to do:
my Regex sub s12 ( $c, $v) {
return / <{$c}> <{$v}> /
}
my regex consonant { <[a .. z] -[aeiou]> }
my regex vowel { <[aeiou]> }
my regex open_syllable { &s12( &consonant, &vowel ) }
"bac" ~~ m:g/ <open_syllable> /;
say $/; # should be 'ba'
推荐答案
你写的基本上是对的,但你需要稍微调整一下语法.首先,您应该像任何其他子程序一样声明您的组合函数.接下来,似乎将一个正则表达式插入另一个,<$r>
是正确的语法,并将函数调用插入到一个正则表达式中,<{my-sub(args)}>
是正确的语法.(调用时不需要在 sub 前面加上 & 号——&
主要用于当你想引用 Callable
而不调用它时.)结合这些小修复并且您的代码有效:
What you wrote is basically right, but you need to tweak the syntax a little. First, you should declare your combining function like any other sub. Next, it seems like to interpolate a regex into another, <$r>
is the right syntax, and to interpolate a function call into a regex, <{my-sub(args)}>
is the right syntax. (No need to prefix the sub with an ampersand when calling it—&
is mostly for when you want to refer to a Callable
without calling it.) Combine these little fixes and your code works:
sub combine(Regex $a, Regex $b --> Regex) {
/ <$a> <$b> /
}
my regex consonant { <[a .. z] -[aeiou]> }
my regex vowel { <[aeiou]> }
my regex open_syllable { <{combine(&consonant, &vowel)}> }
"bac" ~~ m:g/ <open_syllable> /;
say ~$/; # output: ba
这篇关于在 Perl 6 中将正则表达式作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!