Creating a Multiple Choice Quiz System with CGI
Over the last few months, we have looked at a number of techniques that CGI programmers can use to work on their programs. This month, we will look at a multiple-choice quiz system that uses a combination of techniques to create a simple, but effective, system for creating quizzes for our users. By the end of this short project, you will have not only a good idea of how to implement this type of interaction, but a working four-question quiz, as well.
Before we can begin, we will need to decide on a file format which will contain the questions and answers for our quiz. We could put all of the questions and answers inside of the program itself, but moving them to one or more external files will let us reuse the software with other quizzes on our system. Given that this is a simple quiz, let's say that the questions and answers for each quiz are stored in a file whose name is the same as the quiz name. Thus the quiz named “presidents” will be stored in a file named “presidents”, while the quiz named “unix” is stored in a file named “unix”.
Now that we have decided on filenames, we need to decide on a format for the contents of the file. Let's take the easy route, and put one question and its associated possible answers on each line in the file, each separated by tabs, and ending with the letter “a”, “b”, “c” or “d”, that corresponds to the correct answer.
So that the file can contain comments and whitespace, we'll say that any line beginning with a hash mark (#) is considered a comment, to be ignored. The same goes for any line consisting solely of whitespace. Allowing for comments and whitespace makes it possible for us to comment out questions that we no longer want to use, without having to delete them altogether.
Here is a sample quiz on the subject of cranberries, which we will put in a file named, oddly enough, “cranberries”:
# This is the quiz file about cranberries.
# Comment lines contain a hash mark (#) in the # first column, and are ignored, as are lines # containing only whitespace.
What color are cranberries? Red White\ Blue Dark green A What can you make with cranberries? Muffins\ Sauce Steak A and B D
Note that the questions and answers in this file can contain space characters, but not tab characters. This will typically not affect things very much, but it is a consideration to keep in mind. Also, while each line can be as long as needed, the question and its associated answers must remain on a single line of text (that is, must end in a carriage return).
Our quiz program actually consists of two different programs working in concert with each other. The first, askquestion.pl, produces an HTML form that presents the user with a question and a list of possible answers. That form will be submitted to another CGI program, checkanswer.pl, which determines whether the user has selected the correct answer.
Because both of these CGI programs will have to access the same quiz file, it is probably a good idea to centralize such functions in a single Perl 5 object. Such an object would have to read the file and return a question of our choosing from the list of available questions. To make things a bit more interesting, this object should include a method that retrieves a random question from the file, which makes the quiz less predictable for the user.
The object that we will use in our quiz program is shown in Listing 1. All this code means is that you can place a:
statement near the top of both CGI programs to create a Perl object that reads the questions to the “cranberries” quiz. To do this, you can use this statement:
my $quiz = new QuizQuestions("cranberries");For example, you could retrieve the fifth question with:
my @question = $quiz->getQuestion(5);or a random question with:
my @question = $quiz->getRandomQuestion;As you can see, the QuizQuestion object in Listing 1 has nothing to do with CGI programming per se. Even if we were creating a quiz system that wouldn't be used on the Web, this object would be a good starting point. By using an object to represent our data, we have also made it possible to change the file format we are using without modifying the CGI programs that access the data. If we were so inclined, we would be able to move the quiz data into an SQL table, and access it via a database client from within Perl. As long as the interface to the outside world remains the same, our CGI programs wouldn't care.
Now that we have created a fairly simple interface to the quiz data, let's create the first of our two programs, askquestion.pl. This program produces an HTML form which not only asks a question, but also lets the user choose an answer by clicking on the appropriate radio button.
One possible version of the program, shown in Listing 2, is fairly straightforward. It creates one instance of CGI, an object which helps us write CGI programs, and one instance of QuizQuestions, the object we created above. After instantiating these two objects, we then produce a simple HTML form containing four radio buttons that correspond to each possible answer. We then create a submit button and a reset button, and finish creating the HTML form.
However, we also create a hidden field that contains the number of the question the user is answering. This number is returned by the getQuestion and getRandomQuestion methods within QuizQuestions. If you didn't understand previously why we needed to return these values along with the questions and answers, perhaps it will be clearer now. HTTP is a stateless protocol—every request made to a server is independent of any other requests made to it. The quiz requires at least two connections to the HTTP server—one to get the question and produce a form with askquestion.pl, and a second to submit the user's response and check the answer, checkanswer.pl.
The problem is that checkanswer.pl can verify only that the user's answer is correct if it knows which question the user was asked. Since checkanswer.pl is invoked with a separate request to the HTTP server it cannot know which question was selected, unless we have some way of passing that message from the invocation askquestion.pl.
We could have used the hidden field to pass the correct answer along to checkanswer.pl, but this is a bad idea because hidden fields are hidden only from obvious view. If a user were interested in finding the correct answer, he or she would be able to look at the page's HTML source, which would quickly reveal the answer. This way, users know only which question is being asked, not which answer is correct.
Also note that the name of the quiz comes from the query string, which is passed to us in the QUERY_STRING environment variable. This lets us, as mentioned above, use the same quiz program for multiple programs. By changing the value placed in the query string, you can turn this pair of programs into many different quizzes, each with its own set of questions and answers. When we set the action attribute in the <Form> tag, we make sure that it includes not only the name of the program to which the form should be submitted, checkanswer.pl, but also the name of the quiz, which appears in the query string.
As we saw earlier, the form generated by askquestion.pl is submitted to a second CGI program, checkanswer.pl. Checkanswer.pl opens the list of questions, retrieves the question that the user was asked by retrieving the value of the questionNumber form element, which is hidden in the form, and checks the user's answer against the correct one.
If the user answers the question correctly, the program displays a “congratulations” headline along with the correct answer, and asks if the user would like another question.
If the user answers the question incorrectly, the program displays the correct answer, offers some consolation, and asks the user if he or she would like to continue.
Now you can see why you need the getQuestion and the getRandomQuestion method. With getQuestion alone, you can retrieve a question, but not a random selection from the list of questions. But if you had only getRandomQuestion, you would not be able to retrieve the question that the user had asked, and thus would not be able to check the user's answer against the correct one.
The source code for checkanswer.pl is in Listing 3. One obvious flaw of this implementation is that if the site administrator decides to modify the questions file between the time the user receives the question and when he or she submits the form, the question might be marked as wrong. That's because the programs expect the order of the questions will not be modified between the time the question is asked and when it is answered. If you were to insert a new question at the top of the file, this would turn question 1 into question 2, question 2 into question 3 and so on—which would mean that checkanswer.pl would compare the user's answer with an answer to a different question.
Note that we used Perl's eval function to get the actual text of the answer. Perhaps this is simply a personal hang-up, but I hate it when I am told that I answered incorrectly, but no one tells me what the correct answer was. We could have stored the answers in an associative array, but I decided that it would be interesting to use eval to get the value of a variable. In this case, we concatenate the string “$answer” and the value of $rightAnswer, giving us one of the four possible strings “$answerA”, “$answerB”, “$answerC” or “$answerD”. eval is handed that string and returns the value of the variable named in the string.
Now that we have defined QuizQuestions, askquestion.pl and checkanswer.pl, all that remains is to create an HTML file that acts as the initial entrance into the quiz.
<HTML> <Head> <Title>Play our quiz!</Title> </Head> <Body> <H1>Play our quiz!</H1> <P>You can play our cranberry quiz by clicking <a href="/cgi-bin/askquestion.pl?cranberries"> here</a>.</P> </Body> </HTML>
Notice that the URL leading to the initial question must have a quiz name appended to it in the query string. Other than that, though, this is a simple HTML document.
This quiz appears to work pretty well so far, although there are certainly features that you might add—such as a scoreboard, better error-checking when reading the quiz file, or a system that ensures that users don't see the same question twice.
But more important than any of these is the fact that while the format of the question file is easy for programmers to understand, non-programmers who would like to add, delete or modify questions might find the format confusing. Next month we will work on making this system more author-friendly, so that non-programmers can modify entries in the question file via an HTML form.
Reuven M. Lerner has been playing with the Web since early 1993, when it seemed more like a fun toy than the World's Next Great Medium. He currently works as a independent Internet and Web consultant from his apartment in Haifa, Israel. When not working on the Web or volunteering in informal educational programs, he enjoys reading on just about any subject, but particularly politics and philosophy, cooking, solving crossword puzzles and hiking. You can reach him at email@example.com or firstname.lastname@example.org.