# 
# 
# This is my solution for regular quiz 8:
# 
# I opted to ignore words containing non-word characters (which would
# include accented letters, unless ones locale has been set), and to
# consider words to be caseless.
# 
#!/usr/bin/perl

use strict;
use warnings;

use constant SIZE => 4;

my %saw;     # Count of substrings.
my %words;   # Contains first word seen with a substring.

while (<>) {
    s/^\s+//; s/\s+$//;        # Skip leading and trailing spaces.
    next if /[\W_]/;           # Ignore entries with non-word characters.
    next if length () < SIZE;  # Can't participate if too short.
    $_ = lc;
    for (my $i = SIZE; $i <= length; $i ++) {
        my $sub = substr $_ => $i - SIZE, SIZE;
        $words {$sub} = $_ if 1 == ++ $saw {$sub};
    }
}

open my $fq => '> questions' or die "Failed to open questions: $!";
open my $fa => '> answers'   or die "Failed to open answers: $!";

while (my ($sub, $c) = each %saw) {
    next unless $c == 1;
    print $fq $sub, "\n";
    print $fa $words {$sub}, "\n";
}
close $fq or die "Failed to close questions: $!";
close $fa or die "Failed to close answers: $!";

__END__
