I have a problem I am hoping someone can help with (greatly simplified for the purposes of explaining what I am trying to do)...
I have three different arrays:
my @array1 = ("DOG","CAT","HAMSTER");
my @array2 = ("DONKEY","FOX","PIG", "HORSE");
my @array3 = ("RHINO","LION","ELEPHANT");
I also have a variable that contains the content from a web page (using WWW::Mechanize):
my $variable = $r->content;
I now want to see if any of the elements in each of the arrays are found in the variable, and if so which array it comes from:
e.g
if ($variable =~ (any of the elements in @array1)) {
print "FOUND IN ARRAY1";
} elsif ($variable =~ (any of the elements in @array2)) {
print "FOUND IN ARRAY2";
} elsif ($variable =~ (any of the elements in @array3)) {
print "FOUND IN ARRAY3";
}
What is the best way to go about doing this using the arrays and iterating through each element in the arrays? Is there a better way this can be done?
your help is much appreciated, thanks
You can make a regex out of the array elements, but you'll most likely want to disable meta characters and make sure you do not get partial matches:
my $rx = join('\b|\b', map quotemeta, @array1);
if ($variable =~ /\b$rx\b/) {
print "matched array 1\n";
}
If you do want to get partial matches, such as FOXY below, simply remove all the \b sequences.
Demonstration:
use strict;
use warnings;
my @array1 = ("DOG","CAT","HAMSTER");
my @array2 = ("DONKEY","FOX","PIG", "HORSE");
my @array3 = ("RHINO","LION","ELEPHANT");
my %checks = (
array1 => join('\b|\b', map quotemeta, @array1),
array2 => join('\b|\b', map quotemeta, @array2),
array3 => join('\b|\b', map quotemeta, @array3),
);
while (<DATA>) {
chomp;
print "The string: '$_'\n";
for my $key (sort keys %checks) {
print "\t";
if (/\b$checks{$key}\b/) {
print "does";
} else {
print "does not";
}
print " match $key\n";
}
}
__DATA__
A DOG ATE MY RHINO
A FOXY HORSEY
Output:
The string: 'A DOG ATE MY RHINO'
does match array1
does not match array2
does match array3
The string: 'A FOXY HORSEY'
does not match array1
does not match array2
does not match array3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With