Skip to content

Commit c117e00

Browse files
authored
Update regexes.pod6
1 parent b58e2dc commit c117e00

File tree

1 file changed

+35
-7
lines changed

1 file changed

+35
-7
lines changed

doc/Language/regexes.pod6

Lines changed: 35 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1255,17 +1255,45 @@ 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 Interpolation; <$pattern>»
1258+
=head1 X<Regex Interpolation|regex, Regex Interpolation>
12591259
12601260
If you want to build a regex using pattern given at the runtime, regex
12611261
interpolation is what you looking for.
12621262
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+」␤»
12691297
12701298
=head1 Adverbs
12711299

0 commit comments

Comments
 (0)