#!/Users/newby/.local/bin/perl -w

# gbn's possible solution to the Midterm Exam programming
# assignment.  The assignment:

# || Programming exercise (15 points): "mail merge." Create a file with
# || three names, one per line:
# || 
# ||     Dudley Duck
# ||     Peter Panda
# ||     Thomas Crane
# || 
# || Write a Perl program to open and read the names from the file, then
# || output three new files with the skeleton of a form letter using each
# || line's full name (first and last) in the address, but just their first
# || in the salutation.
# || 
# || Required input: the file mentioned above
# || 
# || Required output: One file per input name. The file should be named
# || with the firstname and lastname, but in lower case with no spaces,
# || with .txt at the end (i.e., "Dudley Duck" would become
# || "dudleyduck.txt"). Each file should have four lines, of this form (use
# || the same address for each):
# || 
# || 	Mr. Dudley Duck
# || 	106 Chapman Hall
# || 
# || 	Dear Dudley:
# || 
# || Additional requirement: Use a loop to read & act on the input lines,
# || so that the program would function correctly for other 2-part names.

use strict;

# Input file:
my $infile="midterm-input.txt";

# Open:
open (FH, "<$infile") || die "$infile file open for reading failed: $!";

# Variables, to be filled as list:
my ($firstname, $lastname);

# Get and process all data:
#$/=" ";
#$undef $/;

# Define outside of the loop, perhaps this will be more efficient
# than defining inside the loop:
my $outfile;

while (<FH>) {
#while ( ($firstname, $lastname) = <FH>) {
    chomp; # Need to chomp, elsewise the filenames will be wrong.
    ($firstname, $lastname) = split(/ /, $_);
    # Build output filename and open it:
    print "first=$firstname\tlast=$lastname\n";
#    my $tmp="$firstname$lastname";
#    $tmp =~ tr/[A-Z]/[a-z]/;
#    my $outfile = $tmp . ".txt";

#    my $outfile = lc("${firstname}${lastname}.txt");
    $outfile = lc("${firstname}${lastname}.txt");

    open (OH, ">$outfile") || die "$outfile file open for writing failed: $!";

    # Write output (no \n needed after $lastname):
    print OH 'Mr. ' . $firstname . ' ' . $lastname
	. "\n" . '106 Chapman Hall' . "\n\n" 
	. 'Dear ' . $firstname . ':' . "\n";
    close (OH);
}

close (FH);
exit;
