Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method returning a regex in Perl 6?

I'm only beginning to study classes, so I don't understand the basics.

I want a method to construct regex using attributes of the object:

class TEST {
    has Str $.str;

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

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

When trying to run this program, I get the following error message:

===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

So, what's the right way to do that?

like image 718
Eugene Barsky Avatar asked Apr 22 '18 08:04

Eugene Barsky


1 Answers

Looks like this would work:

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

You are returning an anonymous regex, which can be used as an actual regex, as it's done in the last two sentences.

like image 117
jjmerelo Avatar answered Sep 19 '22 10:09

jjmerelo