Skip to content

Commit 390459d

Browse files
authored
Merge pull request #1652 from perl6/doc-regex-interpolation
Document Regex Interpolation, jnthn++
2 parents 8f105bb + 69cdc07 commit 390459d

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

doc/Language/regexes.pod6

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1255,6 +1255,37 @@ list of predefined subrules is listed in
12551255
L<S05-regex|https://design.perl6.org/S05.html#Predefined_Subrules> of design
12561256
documents.
12571257
1258+
=head1 X<Regex Interpolation|regex, Regex Interpolation>
1259+
1260+
If you want to build a regex using a pattern given at runtime, regex
1261+
interpolation is what you are looking for.
1262+
1263+
There are four ways you can interpolate a string into regex as a pattern.
1264+
That is using C«$pattern», C«$($pattern)», C«<$pattern>» or
1265+
C«<{$pattern.method}>».
1266+
1267+
my Str $text = 'camelia';
1268+
my Str $pattern0 = 'camelia';
1269+
my Str $pattern1 = 'ailemac';
1270+
my Str $pattern2 = '\w+';
1271+
1272+
say $text ~~ / $pattern0 /; # OUTPUT: «「camelia」␤»
1273+
say $text ~~ / $($pattern0) /; # OUTPUT: «「camelia」␤»
1274+
say $text ~~ / $($pattern1.flip) /; # OUTPUT: «「camelia」␤»
1275+
say 'ailemacxflip' ~~ / $pattern1.flip /; # OUTPUT: «「ailemacxflip」␤»
1276+
say '\w+' ~~ / $pattern2 /; # OUTPUT: «「\w+」␤»
1277+
say '\w+' ~~ / $($pattern2) /; # OUTPUT: «「\w+」␤»
1278+
1279+
say $text ~~ / <{$pattern1.flip}> /; # OUTPUT: «「camelia」␤»
1280+
# say $text ~~ / <$pattern1.flip> /; # !!Compile Error!!
1281+
say $text ~~ / <$pattern2> /; # OUTPUT: «「camelia」␤»
1282+
say $text ~~ / <{$pattern2}> /; # OUTPUT: «「camelia」␤»
1283+
1284+
Note that the first two syntax interpolate the string lexically, while
1285+
C«<$pattern>» and C«<{$pattern.method}>» causes L«implicit EVAL|
1286+
/language/traps#<{$x}>_vs_$($x):_Implicit_EVAL», which is a known trap.
1287+
1288+
12581289
=head1 Adverbs
12591290
12601291
Adverbs modify how regexes work and provide convenient shortcuts for

0 commit comments

Comments
 (0)