gpt4 book ai didi

class - 方法在Perl 6中返回正则表达式?

转载 作者:行者123 更新时间:2023-12-04 13:46:05 25 4
gpt4 key购买 nike

我只是开始学习类(class),所以我不懂基础知识。

我想要一种使用对象属性构造regex的方法:

class TEST {
has Str $.str;

method reg {
return
rx/
<<
<[abc]> *
$!str
<!before foo>
/;
}
}

my $var = TEST.new(str => 'baz');
say $var.reg;

尝试运行此程序时,出现以下错误消息:

===SORRY!=== Error while compiling /home/evb/Desktop/p6/e.p6
Attribute $!str not available inside of a regex, since regexes are methods on Cursor.
Consider storing the attribute in a lexical, and using that in the regex.
at /home/evb/Desktop/p6/e.p6:11
------> <!before foo>⏏<EOL>
expecting any of:
infix stopper

那么,什么是正确的方法呢?

最佳答案

看起来像这样工作:

class TEST {
has Str $.str;

method reg {
my $str = $.str;
return
regex {
<<
<[abc]> *
$str
<!before foo>
}
}
}

my $var = TEST.new(str => 'baz');
say $var.reg;
say "foo" ~~ $var.reg;
say "<<abaz" ~~ $var.reg

您将返回一个 anonymous regex,它可以用作实际的正则表达式,就像在最后两个句子中所做的一样。

关于class - 方法在Perl 6中返回正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49963853/

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