I have two arrays, one with search terms and another which is multiple lines fetched from a file. I have a nested foreach statement and am searching for for all combinations, but only the very last match is showing even though I know for a fact that there are many other matches!! I have tried many different versions of the code but here is my last one:
open (MYFILE, 'searchTerms.txt');
open (MYFILE2, 'fileToSearchIn.xml');
@searchTerms = <MYFILE>;
@xml = <MYFILE2>;
close(MYFILE2);
close(MYFILE);
$results = "";
foreach $searchIn (@xml)
{
foreach $searchFor (@searchTerms)
{
#print "searching for $searchFor in: $searchIn\n";
if ($searchIn =~ m/$searchFor/)
{
$temp = "found in $searchIn \n while searching for: $searchFor ";
$results = $results.$temp."\n";
$temp = "";
}
}
}
print $results;
You should always
use strictanduse warningsat the start of your program, and declare all variables at the point of their first use usingmy. This applies especially when you are asking for help with your code as this measure can quickly reveal many simple mistakes.As Raze2dust has said it is important to remember that lines read from a file will have a trailing newline
"\n"character. If you were checking for exact matches between a pair of lines then this wouldn’t matter, but since it’s not working for you I assume the strings insearchTerms.txtcan appear anywhere in the lines offileToSearchIn.xml. That means you need to usechompthe strings fromsearchTerms.txt; lines from the other file can stay as they are.Things like this are made a lot easier by using the
File::Slurpmodule. It does all the file handling for you and will chomp any newlines from the input text if you ask.I have changed your program to use this module so that you can see how it works.