在 Perl 6 中返回正则表达式的方法?
Method returning a regex in Perl 6?
刚开始学习类,基础知识还不了解
我想要一个方法来构造 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
那么,正确的做法是什么?
Using EVAL 解决了我的问题。所以,我想知道,这种方法是否有任何缺点。
class TEST {
has Str $.str;
method reg {
return
"rx/
<<
<[abc]> *
$!str
<!before foo>
/".EVAL;
}
}
my $var = TEST.new(str => 'baz');
say "abaz" ~~ $var.reg; # abaz
say "cbazfoo" ~~ $var.reg; # Nil
看起来这样可行:
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,它可以用作实际的正则表达式,就像在最后两个句子中所做的那样。
刚开始学习类,基础知识还不了解
我想要一个方法来构造 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
那么,正确的做法是什么?
Using EVAL 解决了我的问题。所以,我想知道,这种方法是否有任何缺点。
class TEST {
has Str $.str;
method reg {
return
"rx/
<<
<[abc]> *
$!str
<!before foo>
/".EVAL;
}
}
my $var = TEST.new(str => 'baz');
say "abaz" ~~ $var.reg; # abaz
say "cbazfoo" ~~ $var.reg; # Nil
看起来这样可行:
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,它可以用作实际的正则表达式,就像在最后两个句子中所做的那样。