#!/usr/local/bin/perl -w
use strict;
my %things = (
"apple" => ["red", "round", "plant", "fruit"],
"orange" => ["orange", "round", "plant", "fruit"],
"pumpkin" => ["orange", "round", "plant", "vegetable"],
"ball" => ["red", "round", "toy"],
);
my %kinds;
#
# here we populate %kinds hash with kinds from %things, but of course
# in real life we should do it while populating %things hash
#
foreach my $t (keys %things) {
foreach my $k (@{$things{$t}}) {
$kinds{$k}{$t} = 1;
}
}
# search for "red round plant"
my @search = split (' ',"red round plant");
my %kinds_slice;
#
# we can use slice here only because kinds are strings
# if your kinds are not strings - well, it's another story
#
@kinds_slice{@search} = @kinds{@search};
my %things_sort;
#
# this is boring "count it" loop, but hey,
# we're counting only %kinds_slice, not the whole/all %kinds!
#
foreach my $kind (keys %kinds_slice) {
foreach my $thing (keys %{ $kinds_slice{$kind} }) {
$things_sort{$thing}++;
}
}
#
# all things that match search, sorted
#
print "Matches:\n",join ("\n",map {"$_: $things_sort{$_}"} sort { $thi
+ngs_sort{$b} <=> $things_sort{$a} } keys %things_sort),"\n\n";
#
# or just get the first value to get best match
#
my @matches = sort { $things_sort{$b} <=> $things_sort{$a} } keys %thi
+ngs_sort ;
print "Best match: ".$matches[0]."\n Score: ".$things_sort{$matches[0]
+}."\n";
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, 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, 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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|