Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering elements of an array with elements of another array in Perl 6

Tags:

raku

I want to filter elements of @array which begin with elements of @search:

my @array = "aaaaa" .. "fffff";
my @search = "aaaa" .. "cccc";
.put for @array .grep: /^ @search /;

The problem is it takes 19 seconds. So, I 'precompile' the regex for grep, and the whole program looks like this:

my @array = "aaaaa" .. "fffff";
my @search = "aaaa" .. "cccc";

my $search = "/@search.join('|')/".EVAL;

.put for @array .grep: * ~~ /^ <$search> /;

Now it takes 0.444s.

The question: is there a built-in Perl 6 method to do such things? Something like inserting a junction into a regex...

like image 534
Eugene Barsky Avatar asked Oct 25 '17 13:10

Eugene Barsky


1 Answers

my @array = "aaaaa" .. "fffff";
my @search = "aaaa" .. "cccc";
my $join = @search.join('|');
my $rx = rx{ ^ <{$join}> };

@array.grep( * ~~ $rx ).map( *.put )

You need to create the join string separately of it will evaluate the array join for each match. But the basically gives you what you want without using EVAL.

like image 72
Scimon Proctor Avatar answered Sep 18 '22 12:09

Scimon Proctor