Instead of nested-looping over the words looking for pairs, just count up the number of key words that are found, and go from there. The (working/tested) code below first parses the data into a data structure using XML::Simple (uncomment the Dumper to see what it looks like). Then it "prompts" (i have it hardcoded as a constant for testing) for the input, which it then hashes up into %searchwords. Now, you can start going through each MS_X item, and take the <words> section and split it into words, then count how many of those words exist in the %searchwords dictionary. Just add if($score>=2){...} logic inside the loop.
use strict; use warnings; my $s = do {local $/=undef; <DATA>}; use XML::Simple; my $data = XMLin("<opt>$s</opt>", KeepRoot => 0); #use Data::Dumper; #print Dumper $data; my $search_string = "dog cat cow"; # from input my %searchwords = map { $_ => undef } split ' ', $search_string; while( my ($k, $h) = each %$data ){ my $score = scalar grep( exists $searchwords{$_}, split(/, /, $h->{w +ords}) ); # do whatever based on score. } __DATA__ <MS_1> <loc>c:\data\cat.xml</loc> <words>dog, cat, fish, bird</words> </MS_1> <MS_2> <loc>c:\data\cow.xml</loc> <words>dog, cat, fish, bird, cow, goat</words> </MS_2> <MS_3> <loc>c:\data\snake.xml</loc> <words>dog, cat, fish, bird, snake, orange</words> </MS_3>
One comment on your attempt -- it looks like you were trying to re-read <DATA> inside in the inner loop .. you would have to seek to the beginning tfor that to work, but should just store it in a variable before the loops -- other wise it's a waste of expensive I/O to keep opening the file up.

In reply to Re: Matching combination of words in a tag by davidrw
in thread Matching combination of words in a tag by gzayzay

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.