Search code examples
arraysperl

Match if element of array is a partial match to a string?


I am aware of

if ( grep(/^$pattern$/, @array) ) {...}

which will return true if the entire string is found in an element of the array. However im trying to figure out how to return true if one of the elements in the array is a partial match to the end of the string.

For example:

my @array = (".com", ".net", ".org");
my $domain = "www.example.com";   #<--Returns True
   $domain = "www.example.gov";   #<--Returns False
   $domain = "www.computer.gov";  #<--Returns False, .com not at end

Is there a more elegant way to do this without creating a foreach() and using a m// match against each element?


Solution

  • How about

    my @array = (".com", ".net", ".org");
    my $pattern = join "|", map quotemeta, @array;
    
    if ($domain =~ /(?:$pattern)$/)    # $ matches end of string