# 
# Hi,
# 
# My first qotw.  A few things to decide or explain.
# 
# 1. single quotes and full stops would be ignored, ie can't has the four
# letter sequence cant & S.M.E.R.S.H. would have three smer, mers & ersh.
# Other punctuation would be considered word separators.
# 
# 2. Case will be ignored, Canterbury and cantaloupe have a common substring,
# cant.
# 
# 3. I used a global variable %entries to avoid copying a large hash.  I'd
# rather create the hash in process_words() & pass out a reference to it, but
# this is the Regular Quiz.
# 
# 4. I'd rather use
# 
# open my $answers, ">$Afile"; instead of
# open ANSWERS, ">$Afile";
# 
# as the file handle will be closed for me when $answers goes out of scope but
# I think this is forbidden by the rules.
# 
#!/bin/perl

use strict;
use warnings;

my %entries;

my $file = shift or die "Usage: $0 <file of words>\n";
process_words($file);
write_QandA();
exit;

sub process_words {
    my $input = shift;
    open INPUT, $input or die "Can't open $input: $!\n";
    foreach my $word (<INPUT>) {
        foreach my $substring ( substrings($word) ) {
            $entries{$substring} =
              ( exists $entries{$substring} ) ? "" : $word;
        }
    }
    close INPUT;
}

sub substrings {
    my $allowed_punctuation = q('.);
    my $substring_length   = 4;
    my $string             = lc shift;
    $string =~ tr/$allowed_punctuation//d;
    return
      grep { not /[^a-z]/ }
      map { substr $string, $_, $substring_length }
      0 .. length($string) - $substring_length;
}

sub write_QandA {
    my $Qfile = "questions";
    my $Afile = "answers";
    open QUESTIONS, ">$Qfile" or die "Can't open $Qfile:$!\n";
    open ANSWERS,   ">$Afile"   or die "Can't open $Afile:$!\n";
    foreach my $substring ( sort keys %entries ) {
        unless ( $entries{$substring} eq "" ) {
            print QUESTIONS "$substring\n";
            print ANSWERS $entries{$substring};
        }
    }
    close ANSWERS;
    close QUESTIONS;
}
