#!/usr/bin/perl

use warnings;
use strict;

$\ = $/;

$_ = <>, chomp;
my %words = map { lc $_, 1 } m/[a-z]+/gi;
my @words = keys %words;

my @sentences = map { s/^\s+|\s+$//gr }
				map { split m/[.]\K\s+(?=[A-Z0-9])/ } 
				split m/[!?]\K/;

my %Hash;
for my $word (@words){
	my $i = 0;
	for my $sentence (@sentences){
		$sentence =~ m/\b$word\b/i and push @{ $Hash{ $word } }, $i;
		$i ++;
	}
}

<>;

while(<>){
	chomp;
	m/\w/ or next;
	print "Search results for \"$_\":";
	my %w = map { lc $_, 1 } m/\w+/g;
	my @w = keys %w;
	next if grep { !exists $Hash{ $_ } } @w;
	@w = grep { exists $Hash{ $_ } } @w;
	my %idx;
	map { $idx{ $_ } ++ } map { @{ $Hash{ $_ } } } @w;

	my @idx = grep { @w == $idx{ $_ } } keys %idx;
	print "- \"$_\"" for map $sentences[$_], @idx;
}

