SuperCruncher has asked for the wisdom of the Perl Monks concerning the following question:
All the questions are stored in a simple text file. A sample question looks like this:
Questions in the file are delimited by \n===\n and each question may have a variable number of lines (as number of options can vary and some questions have 'visual aids' etc.)question=When driving towards a bright setting sun, glare can be reduc +ed by option1=closing one eye option2=dipping in the interior mirror option3=wearing dark glasses option4=looking sideways answer=4 answertext=Dark glasses are often used as a fashion item but they do h +ave their practical uses. Low sun in the early morning or evening can + dazzle and distract. Lessen the risk by reducing the glare. Wear dar +k glasses if they help you to see better. category1=car category2=vechicle handling
The idea is that each test has n questions (n is specified in a config file). A script is run on the main questions file that produces a preset number of 'test files'. When the system is eventually ready to 'go live', a random 'test file' is selected and converted to HTML to be displayed to the user.
What I'm having trouble with now is my make_tests.pl script that, as the name implies :-) creates the 'test files'. It is meant to randomly select n questions from the main questions file and save them as a 'test file'. Thanks partially to the above monks and partially to 'The Perl Cookbook', I know have the following code (that is intended to return a random list of n questions):
The function currently seems to return only lines, not whole questions. I think clemburg in particular might have warned me about this, and said that I needed some kind of 'read_record' routine but I've got no idea how to go about this (in particular, how to 'maintain state' or maintain file position between different invocations of the function).sub get_std_test { die +(caller(0))[3].' cannot be called in void context' if not defined wantarray; $/ = "===\n"; # set our delimiter my %config = mcas::get_config(); # returns a hash of all config vars my $count = 0; my @questions; open QUESTIONS, '<questions' or die "Cannot open QUESTIONS file: $!" +; while (<QUESTIONS>) { if (rand($.) < 1) { if ($count == $config{num_questions_per_test}) { last; } else { push @questions, $_; $count++ } } } close QUESTIONS; die "\$count = $count, < num_questions_per_test config var" if ($count < $config{num_questions_per_test}); return @questions; }
If anyone can offer any advice (or even code!), I'd greatly appreciate it.
|
|---|