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

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

我想要一个方法来使用对象的属性构造正则表达式:

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,它可以用作实际的正则表达式,就像它在最后两个句子中所做的那样.

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...