return to first page linux journal archive
keywordscontents

Listing 2. The Original Version of QuizQuestions.pm

#!/usr/bin/perl -w

package QuizQuestions;

use strict;
use diagnostics;

# Get the CGI-enhanced version of
# the Carp
# debugging module, available
# from CPAN, at http://www.perl.com/CPAN
use CGI::Carp;

# All of the questions should be
# in the same directory
my $questionDir = "./";

#
------------------------------
sub new
{
    # Get our arguments
    my $type = shift;
    my ($quizName) = @_;
    my $self = {};

    # Set some initial variables
    my @questions = ();
    my $counter = 0;

    # Open the questions file
    open (QUESTIONS, $questionDir . $quizName) || 
	return "Could not open $quizName ";

    # Loop through the question file
    while (<QUESTIONS>)
    {
	next if /^#/;     # Ignore comment lines
	next unless /\w/; # Ignore whitespace lines

	chomp;

	# Add this question to our list
	$questions[$counter++] = $_;
    }

    close(QUESTIONS);

    # Now turn @questions into
    # an instance variable
    $self->{"questions"} = \@questions;

    bless $self;
}

#
-------------------------------------
sub getQuestion
{
    # Get information about ourself
    my $self = shift;

    # Get the argument, which should be
    # an integer
    my($index) = shift;

    # Get the question corresponding to that
    # number
    my $question = 
	    @{$self->{"questions"}}[$index];

    # Turn that into a list
    my @question = split(/\t/, $question);

    # Add the number of the question to the list
    push(@question, $index);

    # Return the list to the caller
    return @question;
}

#
-----------------------------------------
sub getRandomQuestion
{
    # Get information about ourself
    my $self = shift;

    my @questions = @{$self->{"questions"}};

    # Seed the random number generator
    srand(time);

    # Choose a random number from among the
    #  questions
    my $random_number = int(rand($#questions + 1))
		    + 0;

    # Now invoke getQuestion with our random
    # number
    return ($self->getQuestion($random_number));
}

# Indicate that the module was loaded successfully
1;