Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any difference between m and rx?

Tags:

syntax

regex

raku

They seem to be used interchangeably in the documentation. Is there any difference, even in intent?

like image 822
jjmerelo Avatar asked May 01 '18 06:05

jjmerelo


1 Answers

As the documentation you link to states,

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␤»

So /.../ returns a Regex object that can be passed around as a value, and be used for matching later on and multiple times, and m/.../ returns a Match object having immediately performed the match. When you print a Match object, you get the result of the match, and when you print a Regex object, you get a textual representation of the regex. Using m/.../ in Perl 6 lets you access the implicit Match object, $/:

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.

The distinction is comparable to Python's 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 even when not explicitly asking it to. (Presumably, Perl 6 performs this optimization, too.)

like image 131
sshine Avatar answered Oct 05 '22 03:10

sshine