Skip to content

Commit

Permalink
Clarify interpolation section
Browse files Browse the repository at this point in the history
Attempts to clarify regex interpolation by starting with two examples and a simple explanation.

Leaving in the more complicated examples should people want more.
  • Loading branch information
MorayJ committed Oct 1, 2018
1 parent e696e37 commit 3666b8b
Showing 1 changed file with 22 additions and 10 deletions.
32 changes: 22 additions & 10 deletions doc/Language/regexes.pod6
Expand Up @@ -1446,17 +1446,33 @@ documents.
=head1 X<Regex interpolation|regex, Regex Interpolation>
If you want to build a regex using a pattern given at runtime, regex
interpolation is what you are looking for.
Instead of using a literal pattern for a regex match you can use a variable
that holds that pattern.
This variable can then be 'interpolated' which means it is used as though it is the pattern that it holds.
my Str $pattern = 'camelia';
say 'camelia' ~~ / $pattern /; # OUTPUT: «「camelia」␤»
If the variable to be interpolated is statically typed as a C«Str» or C«str»
and only interpolated literally, then the compiler can optimize it and it runs
much faster (like C«$pattern» above ).
Sometimes you may want to match a generated string in a regex. This can be
done in the following way:
my Str $pattern = 'ailemac';
say 'camelia' ~~ / $($pattern.flip) /; # OUTPUT: «「camelia」␤»
There are four ways you can interpolate a string into regex as a pattern.
That is using C«$pattern», C«$($pattern)», C«<$pattern>» or
C«<{$pattern.method}>».
If the variable to be interpolated is statically typed as a C«Str» or C«str»
(like C«$pattern0» and C«$pattern2» are below) and only interpolated literally
(like the first example below), than the compiler can optimize that and it runs
much faster.
Note that the two examples above interpolate the string lexically, while
C«<$pattern>» and C«<{$pattern.method}>» causes L«implicit EVAL|
/language/traps#<{$x}>_vs_$($x):_Implicit_EVAL», which is a known trap.
Here are examples showing all four ways:
my Str $text = 'camelia';
my Str $pattern0 = 'camelia';
Expand All @@ -1475,10 +1491,6 @@ much faster.
say $text ~~ / <$pattern2> /; # OUTPUT: «「camelia」␤»
say $text ~~ / <{$pattern2}> /; # OUTPUT: «「camelia」␤»
Note that the first two syntax interpolate the string lexically, while
C«<$pattern>» and C«<{$pattern.method}>» causes L«implicit EVAL|
/language/traps#<{$x}>_vs_$($x):_Implicit_EVAL», which is a known trap.
When an array variable is interpolated into a regex, the regex engine handles it
like a C<|> alternative of the regex elements (see the documentation on
L<embedded lists|#Quoted lists are LTM matches>, above). The interpolation
Expand Down

0 comments on commit 3666b8b

Please sign in to comment.