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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With