m 和 rx 之间有什么区别吗?
Any difference between m and rx?
他们似乎是used interchangeably in the documentation。有什么不同吗,即使是在意图上?
正如您 link 所述的文档,
m/abc/; # a regex that is immediately matched against $_
rx/abc/; # a Regex object
/abc/; # a Regex object
[...] Example of difference between m/ /
and / /
operators:
my $match;
$_ = "abc";
$match = m/.+/; say $match; say $match.^name; # OUTPUT: «「abc」Match»
$match = /.+/; say $match; say $match.^name; # OUTPUT: «/.+/Regex»
所以 /.../
returns 一个 Regex
对象,可以作为值传递,并用于稍后和多次匹配,并且 m/.../
returns 立即执行匹配的 Match
对象。当你打印一个 Match
对象时,你会得到匹配的结果,而当你打印一个 Regex
对象时,你会得到正则表达式的文本表示。在 Perl 6 中使用 m/.../
允许您访问隐式 Match
对象,$/
:
Match results are stored in the $/
variable and are also returned from the match. The result is of type Match
if the match was successful; otherwise it is Nil
.
这种区别与 Python 的 re.compile
vs. re.match
/re.search
, and a similar distinction exists in Perl 5 where you can store and re-use a regex with qr/.../
vs. m/.../
and /.../
for direct matching. As @raiph points out, not all occurrences of m/.../
and /.../
result in direct matching. Conversely, Perl 5 precompiles literal (static) regexes 相当,即使没有明确要求。 (据推测,Perl 6 也执行此优化。)
他们似乎是used interchangeably in the documentation。有什么不同吗,即使是在意图上?
正如您 link 所述的文档,
m/abc/; # a regex that is immediately matched against $_ rx/abc/; # a Regex object /abc/; # a Regex object
[...] Example of difference between
m/ /
and/ /
operators:my $match; $_ = "abc"; $match = m/.+/; say $match; say $match.^name; # OUTPUT: «「abc」Match» $match = /.+/; say $match; say $match.^name; # OUTPUT: «/.+/Regex»
所以 /.../
returns 一个 Regex
对象,可以作为值传递,并用于稍后和多次匹配,并且 m/.../
returns 立即执行匹配的 Match
对象。当你打印一个 Match
对象时,你会得到匹配的结果,而当你打印一个 Regex
对象时,你会得到正则表达式的文本表示。在 Perl 6 中使用 m/.../
允许您访问隐式 Match
对象,$/
:
Match results are stored in the
$/
variable and are also returned from the match. The result is of typeMatch
if the match was successful; otherwise it isNil
.
这种区别与 Python 的 re.compile
vs. re.match
/re.search
, and a similar distinction exists in Perl 5 where you can store and re-use a regex with qr/.../
vs. m/.../
and /.../
for direct matching. As @raiph points out, not all occurrences of m/.../
and /.../
result in direct matching. Conversely, Perl 5 precompiles literal (static) regexes 相当,即使没有明确要求。 (据推测,Perl 6 也执行此优化。)