gpt4 book ai didi

raku - 如何将正则表达式作为参数传递给 Perl 6 中的子程序

转载 作者:行者123 更新时间:2023-12-04 22:28:08 25 4
gpt4 key购买 nike

可能我在做一些完全错误的事情,但是有什么方法可以使用子例程修改和组合 regexes 吗?下面的程序无法编译。

sub a(Regex $r1) {
return rx/ <$r1> a /
}

my regex letter_b { b };

my $new = a(letter_b);
say $new;

最佳答案

查看 Regex 的文档,它说:

A named regex can be defined with the regex declarator followed by its definition in curly braces. Since any regex does Callable introspection requires referencing via &-sigil.

my regex R { \N };
say &R.^name; # OUTPUT: «Regex␤»

此外, Grammar 文档(对于概念,而不是类型),它对此进行了更多解释:

The main ingredient of grammars is named regexes. While the syntax of Perl 6 Regexes is outside the scope of this document, named regexes have a special syntax, similar to subroutine definitions:

my regex number { \d+ [ \. \d+ ]? }

In this case, we have to specify that the regex is lexically scoped using the my keyword, because named regexes are normally used within grammars.

Being named gives us the advantage of being able to easily reuse the regex elsewhere:

say so "32.51" ~~ &number;                                    # OUTPUT: «True␤»
say so "15 + 4.5" ~~ / <number> \s* '+' \s* <number> / # OUTPUT: «True␤»

因此,要将命名的正则表达式作为参数传递到 a 子例程中,您只需在它前面加上一个 & 号:
my $new = a(&letter_b);
# ^
# This is what you need!

say $new;
say so "ba" ~~ $new; # OUTPUT: «True␤»
say so "ca" ~~ $new; # OUTPUT: «False␤»

关于raku - 如何将正则表达式作为参数传递给 Perl 6 中的子程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46983611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com