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

Time:02-08

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?

CodePudding user response:

Or using any from List::Util

if ( any { $re = quotemeta $_; $string =~ /$re$/ } @ary )  { ... }

CodePudding user response:

How about

my @array = (".com", ".net", ".org");
my $pattern = join "|", map quotemeta, @array;

if ($domain =~ /(?:$pattern)$/)    # $ matches end of string
  •  Tags:  
  • Related