@@ -1255,17 +1255,45 @@ list of predefined subrules is listed in
1255
1255
L < S05-regex|https://design.perl6.org/S05.html#Predefined_Subrules > of design
1256
1256
documents.
1257
1257
1258
- = head1 X « Regex Interpolation|Regex Interpolation; <$pattern> »
1258
+ = head1 X < Regex Interpolation|regex, Regex Interpolation >
1259
1259
1260
1260
If you want to build a regex using pattern given at the runtime, regex
1261
1261
interpolation is what you looking for.
1262
1262
1263
- sub runtime-regex(Str $pattern --> Regex) { /<$pattern>/ }
1264
-
1265
- my $regex = runtime-regex(get); # INPUT : «\d+»
1266
- my $text = get; # INPUT : «42»
1267
-
1268
- say $text ~~ $regex; # OUTPUT: «「42」»
1263
+ There are two ways you can interpolate a string into regex as a pattern,
1264
+ which are quite similar to interpolate it into a double-quote string.
1265
+ That is using C « <$pattern> » or C « <{$pattern.method}> » .
1266
+
1267
+ my $text = 'camelia';
1268
+ my $pattern = '\w+';
1269
+ my $pattern_ = 'ailemac';
1270
+ say $text ~~ / <$pattern> /; # OUTPUT: «「camelia」»
1271
+ say $text ~~ / <{$pattern}> /; # OUTPUT: «「camelia」»
1272
+ say $text ~~ / <{$pattern_.flip}> /; # OUTPUT: «「camelia」»
1273
+ # say $text ~~ / <$pattern_.flip> /; !!Compile Error!!
1274
+
1275
+ Note that this syntax causes I < implicit EVAL > , that is a known trap.
1276
+
1277
+ When your pattern is a lexical string, there are two more syntax helping you
1278
+ interpolate it.
1279
+
1280
+ my $text = 'camelia';
1281
+ my $string = 'camelia';
1282
+ my $string_ = 'ailemac';
1283
+ say $text ~~ / $string /; # OUTPUT: «「camelia」»
1284
+ say $text ~~ / $($string) /; # OUTPUT: «「camelia」»
1285
+ say $text ~~ / $($string_.flip) /; # OUTPUT: «「camelia」»
1286
+ say $text ~~ / $string_.flip /; # OUTPUT: «Nil»
1287
+ say 'ailemacxflip' ~~ / $string_.flip /; # OUTPUT: «「ailemacxflip」»
1288
+
1289
+ Because it interpolates a string lexically, it doesn't EVAL the string
1290
+ implicitly.
1291
+
1292
+ my $text = '42';
1293
+ my $text_ = '\d+';
1294
+ my $lexical = '\d+';
1295
+ say $text ~~ / $($lexical) /; # OUTPUT: «Nil»
1296
+ say $text_ ~~ / $($lexical) /; # OUTPUT: «「\d+」»
1269
1297
1270
1298
= head1 Adverbs
1271
1299
0 commit comments