Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading