Variable quantifier in perl6

Suppose I want to combine words with at least four letters (and store them in an array), I wrote the following regular expression that works fine:

if ( $text ~~ m:g/(\w ** 4..*)/ ) { my @words = $/; ... } 

Quantifier from 4 to unlimited

 **4..* 

Now, if I try to replace 4 with scalar $ min_length. Both:

 if ($text ~~ m:g/(\w ** $::min_length..*)/) 

and

 if ($text ~~ m:g/(\w ** <$::min_length>..*)/) 

results in a compilation error: Quantifier does not count anything

Is there a way to get a scalar as a quantifier?

+7
regex perl6
source share
2 answers

If the right side of the quantifier ** not a literal of a number or range, but an arbitrary Perl 6 expression, you must enclose it in braces:

 my $text = "The quick brown fox jumps over the lazy dog."; my $min-length = 4; my @words = $text.comb(/ \w ** {$min-length .. *} /); .say for @words; 

Output:

 quick brown jumps over lazy 
+6
source share

I think using .split more natural match, along with .grep :

 my $text = "The quick brown fox jumps over the lazy dog."; my $min-length = 4; say $text.split(/\W+/).grep(*.chars >= $min-length); =============== (quick brown jumps over lazy) 

If you define words as characters between spaces, you can even use the .words method:

 say $text.words.grep(*.chars >= $min-length); =============== (quick brown jumps over lazy dog.) 
+7
source share

All Articles