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

后端 未结 3 1166
渐次进展
渐次进展 2021-01-18 09:09

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

my @array = \         


        
相关标签:
3条回答
  • 2021-01-18 09:40
    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.

    0 讨论(0)
  • 2021-01-18 09:47

    You could try to speed this up by assembling the regexes.

    I am 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 regexes. You can use Perl 5 modules in Perl 6 code by appending a :from<Perl5> (without a preceding space) to a use statement and then accessing its exported symbols (classes, objects, routines, etc.) as if it was a Perl 6 module:

    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( $_ ))});
    
    0 讨论(0)
  • 2021-01-18 09:48

    For this kind of search, you can easily use index

    say (@array X @search).grep( { defined($^a[0].index($^a[1])) } )
        .grep( { $^a[0].index($^a[1]) == 0 } );
    

    This creates a list of Cs, and seeks the second element of the pair within the first; it returns only the list of those that appear in the first position. defined is needed because it will return Nil if it does not find it. It's not faster than your alternative above, but it's in the same ballpark, with 0.03 system time and ~ 0.30 seconds

    0 讨论(0)
提交回复
热议问题