CSCI 4230
Software Tools
Fall 1999
Suugested Solution to Homework #2

(1)    For example:

use strict;

#  open file.
print "Please input file to be process => ";
my $filename = <STDIN>;
open (DATA, "$filename") || die ("can't open file.");

#   Conversion from letter grade to numeric grade.
my %gradeOf = ("A", 4, "A-", 3.6667, "B+", 3.3333,
               "B", 3, "B-", 2.6667, "C+", 2.3333,
               "C", 2, "C-", 1.6667, "D+", 1.3333,
               "D", 1, "D-", 0.6667, "F", 0);

my %courses;            #  Courses taken by a student.
my %numCourses;         #  Number of courses taken by a student.
my %totalGradePoint;    #  Total grade point of a student.

#   Get lines from input file and populate hashes.
while ($_ = <DATA>) {
   chomp;
   my ($course,$student,$grade) = split /,/;
   if ($courses{$student}) {
       $courses{$student} .= ", " . $course;
   }
   else {
       $courses{$student} .= $course;
   }
   $numCourses{$student}++;
   $totalGradePoint{$student} += $gradeOf{$grade};
}

#  Print result.
print "Student report\n",
      "==============\n\n";
foreach (sort keys %courses) {
   print "student $_ has a GPA of " ,
         $totalGradePoint{$_} / $numCourses{$_},
         " and has taken $numCourses{$_} courses: $courses{$_}.\n";
}

exit 0;

(2)    For example,

#!/opt/gnu/bin/perl
use strict;

#   longwords.pl by Kwok-Bun Yue    August 26, 1999
#   Word swith more than 12 different characters.
my $numLimit = 12;
my %chars = ();
my $word;

open(DICT, "words.txt");
open(OUTPUT, ">result.txt");

while ($word = <DICT>) {
   chomp $word;
   %chars = ();
   my @ch = split //, $word;
   foreach (@ch) {
      $chars{$_}++;
   }
   print OUTPUT "$word\n" if (scalar keys %chars >= $numLimit);
}

close OUTPUT;
close DICT;
exit 0;