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

Hi Monks, I am tring to do a matching of multiple words in a tag, i.e to return a tag that contains the combination of two or more words entered. I have written the the below code but it is not working as I hope. Could any monk kindly enlighten my little mind?

print "\nEnter your words (separated by spaces): >> "; chomp(my $line = <STDIN>); my @words = split /\s+/, $line; for($i = 0; $i <= ($#words-1); $i++) { for($j = $i+1; $j <= $#words; $j++) { print "========================================\n"; print "\t", ucfirst(@words[$i]),"\t", ucfirst(@words[$j]),"\n"; print "========================================\n"; local $/=undef; print grep{!/(@words[$i,$j])/}<DATA> =~ m!(<MS_\d+>.*?</MS_\d+ +>)!gs if /(@words[$i,$j])/; } } __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>

Thanks,

gzayzay

Replies are listed 'Best First'.
Re: Matching combination of words in a tag
by davidrw (Prior) on Apr 17, 2006 at 15:15 UTC
    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.