Search code examples
perlstring-matching

In Perl, how can I match one string against a list of other strings?


I want to check an element in an array, $columns[2], against a small list of strings. The way I have it now is;

if (   $columns[2] eq 'string1' 
    || $columns[2] eq 'string2' 
    || $columns[2] eq 'string3' 
    || ...) { 
   ...
}

It seems there must be a better way than all the OR's.


Solution

  • This is exactly what grep is for:

    my $element_exists = 
       grep { $columns[2] eq $_ } qw(string1 string2 ... stringN);
    

    An alternative would be to use first, which will stop processing once it finds a match. This way if you first string matches $columns[2] you don't have to compare the remaining n-1 strings:

    use List::Util qw/first/;
    
    my $element_exists = 
       defined first { $columns[2] eq $_ } qw(string1 string2 ... stringN);
    

    You could also you any (as @ThisSuitIsBlackNot suggests below) for this purpose, the slight difference being that first returns the value of the element that matches the condition, any returns a boolean:

    use List::Util qw/any/;
    
    my $element_exists = 
       any { $columns[2] eq $_ } qw(string1 string2 ... stringN);