#!/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";
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.