'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 1:[1]
Can use any from List::Util
if ( any { $re = quotemeta; $string =~ /$re$/ } @ary ) { ... }
The $ matches the end of the string so the above matches any $string for which $re pattern is at its end (regardless of what comes before in that string).
The quotemeta escapes all "ASCII non-word characters", so (also) things that have a special meaning inside a regex. In this case it turns that . (a pattern matching any character) into \., a literal dot.
The quotemeta has a \Q ... \E form that can be used inside a regex, for
if ( any { $string =~ /\Q$_\E$/ } @ary ) { ... }
But careful with it to not escape other parts of a potentially more complex pattern.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
