CSCI 4230.1
Software Tools
Spring 2001
Suggested Solution to Mid-Term Examination

(1)    For example,

use LWP::Simple;
use strict;
#  Error checking optional
@ARGV < 1 && die "usage: t1aq1.pl url\n";
my $url = $ARGV[0];
my $urlContents = get($url);
if ($urlContents) {
   my @lines = split /\n/, $urlContents;
   my $flag = 0;
   foreach (@lines) {
      $flag = 1 if /<body/i;
      if ($flag) {
          print "$_\n";
          exit if /<\/body>/i;
      }
   }
}
exit 0;

or simply:

use LWP::Simple;
use strict;
#  Error checking optional
@ARGV < 1 && die "usage: t1aq1.pl url\n";
my $url = $ARGV[0];
my $urlContents = get($url);
if ($urlContents =~ /.*\n(.*?<body.*?<\/body>.*?)\n/si) {
   print $1;
}
exit 0;

(2)    (a)    ARRAY(0x3a4c4c): the actual memory location may vary.

(b)    For example:

sub extract {
   my %result = ();
   my $string = shift;
   foreach (split /&/, $string) {
      my ($param, $value) = split /=/;
      $result{$param} = $value;
   }
   %result;
}

There is actually a more elegant solution using map.

(c)    23

(d)    http://dcm.uhcl.edu/someone/test/somepgm.pl?name=Bun+Yue&money=talk
 

(3)    For example,

use strict;
use CGI::Pretty qw(-nosticky);
use DBI;
$|++;
#
# t1aq4.pl
# Kwok-Bun Yue  March 1, 2001
#

# Porting Global constants.
# ODBC DSN
my $DSN = 'demo';

# Global constatns for author information.
my $AUTHOR_EMAIL = 'yue@cl.uh.edu';
my $COPYRIGHT = 'copyright 2001 Kwok-Bun Yue';

# Global CGI object.
my $q = new CGI::Pretty;

# HTTP parameter
my $DIVISION = "division";

# Get HTTP parameters.
my $division = $q->param($DIVISION);

# Main logic
if ($division) {
    displayResultPage($division);
}
else {
    displayErrorPage();
}
exit 0;    #   main.

# displayResultPage
sub displayResultPage {
    my $division = shift;
    my $dbh = DBI->connect("dbi:ODBC:$DSN");

    # Get result.
    my $sqlDivision = $division;
    $sqlDivision =~ s/'/''/g;
    my $sql = "select Program, NumberOfMajors from t1aq4 " .
              "where division = '$sqlDivision' ";
    my $sth = $dbh->prepare($sql);
    $sth->execute();

    my $total = 0;
    my $resultString = "";
    while (my @row = $sth->fetchrow_array) {
        $resultString .= $row[0] . ": " . $row[1] . $q->br;
        $total += $row[1];
    }

    print $q->header,
          $q->start_html(-title=>'Result Page',
                         -author=>$AUTHOR_EMAIL,
                         -meta=>{'copyright'=>$COPYRIGHT}),
          $q->h3("Result for the division $division");
    if ($total) {
        print "There are $total majors:",
              $q->p,
              $resultString;
    }
    else {
        print "No result found.";
    }
    print end_html;
} # displayResultPage

# Error Page: not needed.
sub displayErrorPage {
    print $q->header,
          $q->start_html(-title=>'Error Page',
                         -author=>$AUTHOR_EMAIL,
                         -meta=>{'copyright'=>$COPYRIGHT}),
          $q->h2('Sorry, error');
} # displayErrorPage