How can I interpolate a variable in a Perl 6 regex?

Synopsis 05 mentions that Perl 6 does not interpolate variables into a regular expression, but you can associate an external variable with a template. As far as I can tell, these documents do not mention this feature. I think that people will still want to somehow create a template from a string, so I wonder how this will work.

Here is a program that demonstrates what is happening now. I do not know what is going to happen or what someone was planning. I am inserting a variable into the template. If you look $rat .perl, you will see the variable name. Then I apply the template and it matches. I am changing the value of a variable. Now the template does not match. Change it to something else that will work, and it will again match:

my $target = 'abcdef';

my $n = 'abc';
my $r = rx/ ( <$n> ) /;

# the smart match like this doesn't return a Match object
# https://rt.perl.org/Ticket/Display.html?id=126969
put 'rx// directly: ',
    $target ~~ $r
        ?? "Matched $0" !! 'Misssed';

# now, change $n. The same $r won't match.
$n = 'xyz';

put 'rx// directly: ',
    $target ~~ $r
        ?? "Matched $0" !! 'Misssed';

# now, change back $n. The same $r does match.
$n = 'ab';
put 'rx// directly: ',
    $target ~~ $r
        ?? "Matched $0" !! 'Misssed';

If this is what he should do, great. The documents here are lightweight, and tests (de facto specifications) are not complicated for such long-range behavior.

I could do extra work to close the copy (and maybe more work than I show, depending on what is in $n), which I find unperly:

my $r = do {
    my $m = $n;
    rx/ <$m> /;
    };

, "" ( , /o ). , Regex. , .

my $r = rx/ .... /.finalize;  # I wish!

, Perl 6 , . Perl 6 . , . , token rule , , . , subrule factory.

?

+5
1

, , EVAL.

, , , . , <{...}>,

/ <{ BEGIN compute-string-once-at-compile-time }> /

, ...

+4

Source: https://habr.com/ru/post/1662377/


All Articles