Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable quantifier in perl6

Tags:

regex

raku

Suppose i want to match words with at least 4 letters, (and store them in an array), I have written the following regex, which works fine:

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

The quantifier being from 4 to unlimited

**4..*

Now if I try to substitute 4 with a scalar $min_length. Both:

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

and:

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

results in an error at compilation: Quantifier quantifies nothing

Is there a way for having a scalar as a quantifier?

like image 369
Mikkel Avatar asked Jun 03 '17 19:06

Mikkel


2 Answers

When the right-hand side of the ** quantifier is not a number or range literal, but an arbitrary Perl 6 expression, you have to 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
like image 128
smls Avatar answered Sep 16 '22 14:09

smls


I think using .split is a more natural fit, together 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 the characters between whitespace, you can even use the .words method:

say $text.words.grep(*.chars >= $min-length);
===============
(quick brown jumps over lazy dog.)
like image 44
Elizabeth Mattijsen Avatar answered Sep 16 '22 14:09

Elizabeth Mattijsen