Listing 1: The version of edit-quizfile that displays the form
#!/usr/bin/perl -w
use strict;
use diagnostics;
use CGI; # Available from http://www.perl.com/CPAN
use QuizQuestions;
# Maximum index for questions (starting at 0)
my $MAX_QUESTIONS = 10;
# Create an instance of CGI
my $query = new CGI;
# Print the MIME header that we will always use
print $query->header("text/html");
# Determine how we were invoked
my $request_method = $query->request_method;
# If we were invoked via POST, then ignore things for now
if ($request_method eq "POST")
{
print $query->start_html(-title => "Not yet implemented");
print "Sorry, the POST part of this program isn't yet written.</P>\n";
print $query->end_html;
}
else
{
# If the query string is empty, then produce a page of HTML
# containing ISINDEX
if ($query->param("keywords") eq "")
{
print $query->start_html(-title => "Enter a quiz name");
print "Please enter the name of the quiz you want ";
print "to create or edit in the below .</P>\n";
print "<ISINDEX>\n";
print $query->end_html;
}
else
{
# Get the name of the quiz
my $quizname = $query->param("keywords");
# Create a new instance of QuizQuestions
my $questions = new QuizQuestions($quizname);
# Read the questions from disk, ignoring errors
# (since we will happily create a new quiz)
$questions->loadFile;
# Create the header for the HTML page
print $query->start_html(-title => "Create/Edit a quiz");
# Define a form
my $script_name = $query->script_name;
print "<Form method="POST" action="$script_name">\n";
# Create the text element for the quiz name
print "Editing quiz: <input type="text" name="quizname" ";
print "value="$quizname"></P>\n";
print "<HR>\n\n";
# Now create one form element for each existing question
my $counter = 0;
foreach $counter (0 .. $MAX_QUESTIONS)
{
# Get a particular question
my ($qtext, $ansA, $ansB, $ansC, $ansD, $correct)
= $questions->getQuestion($counter);
# Question text
print "<H2>Question $counter</H2>\n";
print "Question text: <input type="text" ";
print "name="question-$counter" value="$qtext" ";
print "size="30"></P>\n";
# Answer A
print "Answer A: <input type="text" value="$ansA" ";
print "name="answer-a-$counter" size="30"></P>\n";
# Answer B
print "Answer B: <input type="text" value="$ansB" ";
print "name="answer-b-$counter" size="30"></P>\n";
# Answer C
print "Answer C: <input type="text" value="$ansC" ";
print "name="answer-c-$counter" size="30"></P>\n";
# Answer D
print "Answer D: <input type="text" value="$ansD" ";
print "name="answer-d-$counter" size="30"></P>\n";
# Correct answer
print "Correct answer: <select name="correct-$counter">\n";
my $letter = "";
foreach $letter ("a","b","c","d")
{
print "<option ";
print "selected " if ($letter eq $correct);
print "$letter>$letter\n";
}
print "</select>\n";
print "<HR>\n\n";
}
# Now that the loop is complete, we can finish things up
print '<input type="submit" value="Save changes">', "\n";
print "</HTML>\n";
print $query->end_html;
}
}