0

Any simple solution that Perl supports, which can sort results based on words occurring in array from grep?

For example you have a database which gets results from array grep and you want to show results first with the most repeated word which is matched.

Like a search engine which gives results by relevance.

Does that exists in Perl like in this expression:

@array_relevance = grep(/given_term/i, @old_array);

or

@array_relevance = grep{$_ =~ /given_term/i}@old_array;

where @array_relevance shows results first where "given_term" is occurring the most(like 5 times) and then shows results where "given_term" is occurring the least(4,3,2,1 times) descending

I mean "@old_array" is the data which contains multiple lines and it is a database which is in text file where there are titles, descriptions, time of submitted post etc.

Example of @old_array:

@old_array = "Title:Best marketing firm, Description:Check us out, we have many products which are innovative, Time of post:14:05:2015";

Then @array_relevance with grep selects its content which is requested showing results first which contain the most same terms descending.

Hope its understandable.

Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174

1 Answers1

0

It's difficult to figure out exactly what you need without any data, but try out the following:

use warnings;
use strict;

my @old = qw(nine one one one two three three);
my @given_terms = qw(one two three);

my %seen;
%seen = map {$_ => ++$seen{$_}} @old;

print "$_\n" for sort {$seen{$b} <=> $seen{$a}} @given_terms;
stevieb
  • 9,065
  • 3
  • 26
  • 36
  • 1
    Wouldn't building `%seen` without a `for` loop make more sense, so you're not iterating `@old` multiple times grepping it? And then doing the sort from `@given_terms` rather than `keys`? – Sobrique Aug 18 '15 at 19:41
  • Yes, thanks Sobrique. I was looking at the problem backwards. – stevieb Aug 18 '15 at 19:52