Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw


by TStanley (Canon)
on Oct 12, 2001 at 03:41 UTC ( #118371=sourcecode: print w/replies, xml ) Need Help??
Category: Miscellaneous
Author/Contact Info Thomas Stanley
Description: Games::QuizTaker is the OO module implementation of my script. I have also uploaded this module to CPAN, and as of 11 Oct 01, I am waiting for a response back.
UPDATE: It was approved on 11 Oct 01.
UPDATE: Version 1.02 released on 3 Nov 01
UPDATE: Version 1.03 released on 15 Nov 01
UPDATE: Version 1.04 released on 21 Nov 01
UPDATE: Version 1.06 released on 15 Dec 01
UPDATE: Version 1.24 released on 05 Feb 03
package Games::QuizTaker;
use strict;
use vars qw($AUTOLOAD $VERSION);
use Fcntl qw/:flock/;
use Text::Wrap;
use Carp;


  my ($self)=@_;
  $AUTOLOAD=~/.*::[sg]et(_\w+)/ or croak "No such method: $AUTOLOAD";
  exists $self->{$1} or croak "No such attribute: $1";
  return $self->{$1};

  my $self=shift;
  undef $self;

sub new{
    bless{ _Delimiter        => $arg{Delimiter}|| "|",
       _Answer_Delimiter => $arg{Answer_Delimiter}|| " ", 
           _Score            => $arg{Score}|| undef,
           _FileLength       => "0",
           _FileName         => $arg{FileName}||croak"No FileName give
       _Max_Questions    => "0",
sub load{
  my ($self,$Data)=@_;
  my $Question_File=$self->get_FileName;
  my $Separator=$self->get_Delimiter;
  my $Answer_Sep=$self->get_Answer_Delimiter;
  my ($question_number,$count);

  if($Answer_Sep eq $Separator){
    croak"The Delimiter and Answer_Delimiter are the same";

  open(FH,"$Question_File")||croak"Can't open $Question_File: $!";
    my @sorter;
    if(/^$/ or /^#/){}else{
      my $sep=qq"\\$Separator"; 
      @sorter=split /$sep/;
      $question_number=shift @sorter;
      my $ref=\@sorter;
  close FH;
  return $Data;   

sub generate{
  my ($self,$Data,$Max_Questions)=@_;
  my $Total_Questions=$self->get_FileLength;
  my $FileName=$self->get_FileName;
  $Max_Questions = $Total_Questions unless defined $Max_Questions;

  croak"Number of questions in $FileName exceeded"
    if $Max_Questions > $Total_Questions;

  croak"Must have at least one question in test"
    if $Max_Questions < 1;


  my %Randoms=();
  my @Randoms=();
  my %Test_Questions=();
  my %Test_Answers=(); 
    my $question_number=int(rand($Total_Questions)+1);
    redo if exists $Randoms{$question_number};

  @Randoms=keys %Randoms;

  for(my $D=0;$D<$Max_Questions;$D++){
    $Test_Answers{$Randoms[$D]}=pop @{$$Data{$Randoms[$D]}};
    $Test_Questions{$Randoms[$D]} = $$Data{$Randoms[$D]};
   return \%Test_Questions,\%Test_Answers,\@Randoms; 

sub test{
  my ($self,$Questions,$Answers,$Randoms)=@_;
  my $Answer_Sep=$self->get_Answer_Delimiter;
  my $Max=$self->get_Max_Questions;
  my ($answer,$key,$line,$question_answer);
  my $question_number=1;
  my $number_correct=0;
  my $asep=qq"\\$Answer_Sep";

  system(($^O eq "MSWin32"?'cls':'clear'));

    $key=shift @$Randoms;
    print"Question Number $question_number\n";

    foreach $line(@{$$Questions{$key}}){
      print wrap("","","$line\n");

    print"Your Answer: ";
    $answer=uc $answer;
    $question_answer=uc $question_answer;

    my $ln=length($question_answer);

        warn"Answer_Delimiter doesn't match internally";
      if($Answer_Sep eq " "){ }else{
        $question_answer=~s/$asep/ /;

    if($answer eq $question_answer){
      print"That is correct!!\n\n";
      print"That is incorrect!!\n";
      print"The correct answer is $question_answer.\n\n";
  my $Final=$self->get_Score;
  if(defined $Final){

sub shuffle{
  ## Fisher-Yates shuffle ##
  my ($self,$array)=@_;
  my $x;
    my $y=int rand ($x+1);
    next if $x == $y;

sub Final{
  my ($self,$Correct,$Max)=@_;
  if($Correct >= 1){
    my $Percentage=($Correct/$Max)*100;
    print"You answered $Correct out of $Max correctly.\n";
    printf"For a final score of %02d%%\n",$Percentage;
    print"You answered 0 out of $Max correctly.\n";
    print"For a final score of 0%\n";

sub set_FileLength{
  my $self=shift;
  my $count=shift;

sub set_Max_Questions{
  my $self=shift;
  my $Questions=shift;

sub get_FileLength{
  my $self=shift;
  return $$self{_FileLength};

sub get_Max_Questions{
  my $self=shift;
  return $$self{_Max_Questions};

sub get_FileName{
  my $self=shift;
  return $$self{_FileName};

sub get_Delimiter{
  my $self=shift;
  return $$self{_Delimiter};

sub get_Answer_Delimiter{
  my $self=shift;
  return $$self{_Answer_Delimiter};

sub get_Score{
  my $self=shift;
  return $$self{_Score};

## Debug Functions ##
sub Print_Object{
  my ($self,$structure)=@_;
  require Data::Dumper;

  if(defined $structure){
    print Data::Dumper->Dumper($structure);
    print Data::Dumper->Dumper($self); 

sub get_VERSION{
  my $self=shift;
  return $VERSION;


=head1 NAME

Games::QuizTaker - Create and take your own quizzes and tests


     use Games::QuizTaker;
     my $Q=Games::QuizTaker->new(FileName=>"sampleqa",Score=>1);
     my %Data=();
     my $rData=$Q->load(\%Data);
     my ($rQuestions,$rAnswers,$rRandoms)=$Q->generate(\%Data);


=over 5

=item new

C<< new("FileName"=>"FILENAME","Delimiter"=>"Delimiter",Answer_Delimit
+er=>"Delimiter",Score=>"1"); >>

This creates the Games::QuizTaker object and initializes it with two
parameters. The FileName parameter is required, and the Delimiter is
optional. The Delimiter is what is used to separate the question and
answers in the question file. If the Delimiter parameter isn't passed,
it will default to the pipe ("|") character. The Answer_Delimiter is
used for questions that have more than one correct answer. If the
Answer_Delimiter parameter isn't passed, it will default to a space.
When answering the questions within the test that have more than one
answer, put a space between each answer. There is also a parameter cal
Score that also can be passed to the object. If set, this parameter wi
print out a final score, giving the number of questions answered corre
and the overall percentage. By default, this is turned off. 

=item load

C<< $refHash=$QT->load(\%Data); >>

This function will load the hash with all of the questions and answers
from the file that you specify when you create the object. It also set
another parameter within the $QT object called FileLength, which is th
total number of questions within the file. It will also check to see i
the _Answer_Delimiter parameter is the same as the _Delimiter paramete
If they are the same, then the program will croak.

=item generate

C<< ($refHash1,$refHash2,$refArray1)=$QT->generate(\%Data,$Max); >> 

This function will generate the 2 hashes and 1 array needed by the tes
function. The first reference ($refHash1) are the questions that will 
asked by the test function. The second reference ($refHash2) are the a
to those questions. And $refArray1 is a sequence of random numbers tha
+t is
generated from the total number of questions ($Max) that you wish to a
The $refArray1 is also randomized further after its generation by the
internal _shuffle function which is a Fisher-Yates shuffle. If the max
number of questions you wish to answer on the quiz ($Max) is not passe
+d to
the function, it will default to the maximum number of questions in th
+e file
(determined by the FileLength parameter within the object). It will al
+so set
the Max_Questions parameter within the object, which will be later use
+d by
the test function to keep track of the number of questions printed out

=item test

C<< $QT->test($refHash1,$refHash2,$refArray1); >>

This function will print out each question in the Questions hash, and 
for a response. It will then match that response against the Answers h
If there is a match, it will keep track of the number of correct answe
+rs, and 
move on to the next question, other wise it will give the correct answ
+er, and
go to the next question. After the last question, it will pass the num
correct and the max number of questions on the test to the _Final func
which prints out your final score.


=head1 EXPORT

None by default


There is a single function available for debugging. When called, it wi
print out the contents of the object and its parameters.

Special thanks to everyone at for their suggestio
and contributions to this module, and to Damian Conway for his excelle
book on Object Oriented Perl

Also, I would like to thank Chris Ahrends for his suggestions to impro
+ve this module, and to Mike Castle for pointing out a typo in my POD.

=head1 AUTHOR

Thomas Stanley

I can also be found at as TStanley. You can direc
any questions relating to this module there.


Copyright (C)2001-2003 Thomas Stanley. All rights reserved. This progr
+am is free
software; you can redistribute it and/or modify it under the same term
+s as
Perl itself.
=head1 SEE ALSO


Replies are listed 'Best First'.
Re: Games::QuizTaker
by merlyn (Sage) on Oct 12, 2001 at 06:12 UTC
Re: system('clear')
by belg4mit (Prior) on Nov 17, 2001 at 10:58 UTC
    There are portable modules to do that. Or at least, do it once outside of the subroutine and save the value to a variable.

    perl -p -e "s/(?:\w);([st])/'\$1/mg"

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: sourcecode [id://118371]
[choroba]: My recent record is 10km in 1 hour :)
[perldigious]: Nice erix... perldigious' legs are so sore from portaging his kayak from place to place last weekend he can barely hobble 12m. :-)
[erix]: you're faster than me then :)
[erix]: well, at the moment, that is :)
[erix]: I should lose some weight although I keep telling myself that I'm doing extra training by lugging it along
[erix]: I saw a common kingfisher and a couple of bullfinches
[erix]: bullfinch ( a male and a female )
erix learned the word 'portaging' not so long ago (from vikings lugging their ships from one river-system to another)

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (8)
As of 2017-05-24 12:44 GMT
Find Nodes?
    Voting Booth?