Perl Checking if a scalar contains one of the elements in an array

后端 未结 3 984
傲寒
傲寒 2021-01-25 04:49

I have an array

my @array = qw/FOO BAR BAZ/;

and a scalar read from a file containing data like



        
相关标签:
3条回答
  • 2021-01-25 05:41

    That is exactly what grep is for. Here's a small snippet:

    use strict;
    use warnings;
    
    my $str = "+++123++585+++FOO";
    my $blank = "+++123++585+++XYZ";
    my @array = qw/FOO BAR BAZ/;
    print grep {$str =~ $_} @array, "\n";
    print grep {$blank =~ $_} @array, "\n";
    

    This would just return:

    FOO
    

    grep, reduce and map are what we call higher order functions in FP world, though reduce might be called fold there. Have a look at MJD's Higher Order Perl for more of these.

    • grep
    • map
    • reduce
    • Higher Order Perl
    0 讨论(0)
  • 2021-01-25 05:50

    Yes, there is far better way. You can construct regular expression. It will be alternatives of fixed strings which is fortunately translated into trie (Aho-Corasick) which leads into linear search time. It is the most efficient way at all.

    my @array = qw/FOO BAR BAZ/;
    my $re = join '|', map quotemeta, @array;
    $re = qr/$re/;
    
    for my $string (@strings) {
      if ($string =~ $re) {
        ...
      }
    }
    
    0 讨论(0)
  • 2021-01-25 05:53

    You can create a regex that matches all of the @array:

    my $regex = join '|', map quotemeta, @array;
    $string =~ $regex;
    
    0 讨论(0)
提交回复
热议问题