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

Folks, How do I EXACTLY match a string (containing one or more words) with another string?
Example : Need to match
$str_to_find="Information received correctly"
from an array of strings @Output where string to match from can be :
$output[i]="The form Information recieved correctly on Tuesday".
So this would be the ONLY correct match. But
$output[j]="The Information from you was received today correctly "
is not considered a match. Also, following should not be matched (output found on different lines:
$output[1]="Information" $output[1]="received" $output[1]="correctly"
Any help is appreciated. Thanks in advance

Replies are listed 'Best First'.
Re: Match multiple words in a string ?
by gaal (Parson) on Jul 23, 2004 at 21:57 UTC
    Step one is the naive approach of searching with a regular expression:

    @matches = grep /$str_to_find/, @Output;  # WRONG

    This gives you those strings that did match. But it breaks once $str_to_find contains data that is parsed as regexp metacharacter, since these modify the behavior of the match -- you can get both false positives and miss on true matches.

    So the solution is to quotemeta $str_to_match first, and match against that:

    $quoted_str_to_match = quotemeta $str_to_match; @matches = grep /$quoted_str_to_match/, @Output;

    You can read up on quotemeta and \Q in perlre.

    Update: D'oh! TMTOWTDI, but friedo's way is much simpler in this case :-)

    Still, quotemeta/\Q are good to know about.

Re: Match multiple words in a string ?
by TrekNoid (Pilgrim) on Jul 23, 2004 at 22:12 UTC
    As long as special characters aren't involved, shouldn't the following work?

    foreach $output (@output) { if ($output =~ /$str_to_find/) { print "$output\n"; } }
    Trek
Re: Match multiple words in a string ?
by friedo (Prior) on Jul 23, 2004 at 21:53 UTC
    Use the substr function.

    Pay no attention to the crazy man.

      I think you mean the index function?


      Examine what is said, not who speaks.
      "Efficiency is intelligent laziness." -David Dunham
      "Think for yourself!" - Abigail
      "Memory, processor, disk in that order on the hardware side. Algorithm, algoritm, algorithm on the code side." - tachyon
        Doh! I really should refrain from posting when decaffeinated.
Re: Match multiple words in a string ?
by mifflin (Curate) on Jul 23, 2004 at 22:08 UTC
    You can used grep to return an array of all the records that matched your string...
    @matched = grep {/Information received correctly/} @output;