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

Hello Monks, I'm a newbie and I'm not having much success in attempting to loop trough an array searching for substrings contained in another array and when found, remove them. I tried this
# @quadruple contains longer strings # @triple contains shorter strings foreach $aaaa(@quadruple) { $idx = 0; while ($triple[$idx]) { if ($aaaa =~(/$triple[$idx]/gs)) {push (@common1, $idx); } $idx++; } } foreach $xx(@common1) {splice (@triple,$xx,1) }
Summing up: two arrays, both with strings as elements; I need to find which strings in @triple matches as substrings of @quadruple. Example "United Nations Children Fund" in @quadruple should match against "United Nations Children" in @triple. That done, I need to remove the matched string from @triple WITHOUT leaving an undef hole, cause I have to process that array the same way later. Hope it is clear. Thanks a lot for any help and suggestion. Livius

Replies are listed 'Best First'.
Re: searching in array elements substrings contained in another array
by eff_i_g (Curate) on Nov 17, 2008 at 20:42 UTC
    To expand on what has already been suggested, use quotemeta or \Q and \E to escape data that is being placed inside a regexp; see perlre.
      Thanks, now it works great! Thanks to eff_i_g, too, for the added suggestions. Grateful for your help, have my best greetings Livius
Re: searching in array elements substrings contained in another array
by ccn (Vicar) on Nov 17, 2008 at 20:13 UTC
    foreach my $q (@quadruple) { @triple = grep {$q !~ /$_/} @triple; }
      Thank you for the ultrafast reply... but it seems it soesn't work... Or better: the first cycle works, but when it comes to use the previously processed array (@triple), a long list of warning comes:
      Use of uninitialized value in pattern match (m//)
      and the matches don't work. Printing the two arrays gives that the matches have not been removed... Any idea? Thank you again Livius

        How can undef values fall into @triple array?

        Anyway here is the fix:

        foreach my $q (@quadruple) { @triple = grep {$_ and $q !~ /$_/} @triple; }