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

Eug*_*sky 6 class private-members perl6

我只是开始上课,所以我不了解基础知识.

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

class TEST {
    has Str $.str;

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

my $var = TEST.new(str => 'baz');
say $var.reg;
Run Code Online (Sandbox Code Playgroud)

尝试运行此程序时,我收到以下错误消息:

===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
Run Code Online (Sandbox Code Playgroud)

那么,这样做的正确方法是什么?

jjm*_*elo 9

看起来这样可行:

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
Run Code Online (Sandbox Code Playgroud)

你正在返回一个匿名的正则表达式,它可以用作实际的正则表达式,就像它在最后两个句子中所做的那样.

  • 这个答案的关键点是使用词法别名`my $ str = $!str`.这是因为正则表达式实际上是在光标上调用的*方法*(基本上属于正则表达式引擎的对象),因此没有可用于解析`$!str`属性的`self`.此外,属性不是闭包的一部分,因此您需要词法别名. (2认同)