Filtering array elements with elements of another array in Perl 6

I want to filter @array elements that start with @search elements:

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

The problem is that it takes 19 seconds. So, I'm precompile ' 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.

Question: Is there a built-in Perl 6 method for performing such tasks? Something like inserting junction in regex ...

+5
source share
2 answers

You can try to speed this up by collecting regular expressions.

I'm not sure how to do this using pure Perl 6, but Regexp::Assemble is a Perl 5 module that can do this for Perl 5 regular expressions. You can use Perl 5 modules in Perl 6 code by adding :from<Perl5> (without the previous space) to the use statement, and then accessing its exported characters (classes, objects, routines, etc.), as if it was Perl 6:

 use v6; use Regexp::Assemble:from<Perl5>; my @array = "aaaaa" .. "fffff"; my @search = "aaaa" .. "cccc"; my $ra = Regexp::Assemble.new; $ra.add( @search ); $ra.anchor_string_begin(1); .put for @array.grep({so($ra.match( $_ ))}); 
+3
source
 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 a connection string separately from it to evaluate the union of the array for each match. But basically gives you what you want without using EVAL.

+2
source

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


All Articles