sunfish has asked for the wisdom of the Perl Monks concerning the following question:

Hello- I am a beginning Perl programmer and I have been working on this problem for days. I want to loop through an array of motifs and find matches by looping through a second array. I have tried everything that I can think of and I either get no result,one match or an infinite loop. The code below only gives one match. Thanks so much. Sunfish
$size_array = scalar @car; for($k=0; $k<$size_array; $k++) { foreach $car(@car) { if ($make[$k] =~ /$car/) { push (@shop, $make[$k]); print cftr2dmatch2 "@shop"; next; } else { next; } } }
}

Replies are listed 'Best First'.
Re: regular expressions and nested loops
by Errto (Vicar) on Aug 26, 2007 at 02:26 UTC
    I don't see any fundamental problems here except one: in your outer loop you're iterating over the size of the array @car, when logically it seems that you want to iterate over @make. To reduce your confusion, you can just use foreach-style loops for both:
    foreach my $make (@make) { foreach my $car(@car) { if ($make =~ /$car/) { push (@shop, $make); print cftr2dmatch2 "@shop"; } } }
    I also removed the calls to next which you don't need because the foreach loop will take care of that for you. Also, if cftr2dmatch2 is a function, make sure it is defined in your code at some earlier point, otherwise it will be treated as a filehandle. To avoid this problem say  print cftr2dmatch2("@shop"); instead. Also be sure to add use warnings; at the top of your code.