CSCI 4230
Software Tools
Spring 2000
Suugested Solution to Homework #4

(1)    For example, a lousy one:

use strict;
#
#    h4parse.pl
#        This program parses the input file
#        h4glossary.txt and stores the
#        definition of all mortgage terms
#        in a perl UDB.
#    It is assumed that all terms and definitions
#    are enclosed by: <b>term: </b>definition</b>
#    after the second HR.
#
@ARGV < 1 && die "Usage parse.pl filename" ;
open(IN, $ARGV[0]);

my $body = "";
while ($_ = <IN>) {
   chomp;
   $body .= "$_ " if ($_);
}
$body =~ s/&quot;?/"/g;
$body =~ s/&amp;?/&/g;

my %hash;
dbmopen(%hash, "h4dbm", 0666) || die "Can't open hash file.";

#  Alternate solution to populate %hash
    %hash = ();
    while ($body =~ /<b>(.*?):*\s*<\/b>(.*?)<\/p>/gi) {
      $hash{$1} = $2;
    }

#  %hash = $body =~ /<b>(.*?):*\s*<\/b>(.*?)<\/p>/gi;
dbmclose(%hash);

foreach (sort keys %hash) {
   print "$_ => $hash{$_}\n";
}

exit 0;

(2)    For example,

use strict;
#   h4serach.pl

my %hash;
dbmopen(%hash, "h4dbm", 0644) || die "Can't open hash file.";

print "Please input a keyword=>";
my $key = <STDIN>;
chomp $key;
my $result = "";
my $i=1;
foreach (sort keys %hash) {
   $result .= "[" . $i++ . "]$_: $hash{$_}\n" if (/$key/i || $hash{$_} =~ /$key/i);
}

print $result;
dbmclose(%hash);
exit 0;