Interpolate a variable into a regular expression

I'm used to Perl, but new to Perl 6

I want to place the regular expression in a text variable, as I would do in perl5:

my $a = 'abababa'; my $b = '^aba'; if ($a =~ m/$b/) { print "True\n"; } else { print "False\n"; } 

But if I do the same in Perl6, this will not work:

 my $a = 'abababa'; my $b = '^aba'; say so $a ~~ /^aba/; # True say so $a ~~ /$b/; # False 

I am puzzled ... What am I missing?

+7
regex perl6
source share
1 answer

You need to take a closer look at Quoting Constructs .

In this case, attach the LHS part, which is a separate token with angle brackets or <{ and }> :

 my $a = 'abababa'; my $b = '^aba'; say so $a ~~ /<$b>/; # True, starts with aba say so $a ~~ /<{$b}>/; # True, starts with aba my $c = '<[0..5]>' say so $a ~~ /<$c>/; # False, no digits 1 to 5 in $a say so $a ~~ /<{$c}>/; # False, no digits 1 to 5 in $a 

enter image description here

Another story is when you need to pass a variable to the limit quantifier. Here you need to use only curly braces:

 my $ok = "12345678"; my $not_ok = "1234567"; my $min = 8; say so $ok ~~ / ^ \d ** {$min .. *} $ /; # True, the string consists of 8 or more digits say so $not_ok ~~ / ^ \d ** {$min .. *} $ /; # False, there are 7 digits only 

enter image description here

+4
source share

All Articles