#!/usr/local/bin/perl -- -*- C -*- use CGI; srand(); $quest = 10.0*rand();#CREATE RANDOM VALUES $quest = int(1000*$quest)/1000;#ROUND APPROPRIATELY $query = new CGI; print $query->header; print $query->start_html("q2_rand.pl, Numerical Input Example"); print $query->start_form; if($query->param('quest') eq ""){$query->param('quest',$quest);} #IF THIS IS THE FIRST TIME, ASSIGN TO HIDDEN print $query->hidden('quest');#THEN HIDE IT $quest = $query->param('quest');#RETREIVE IT print <<EOF; <P> How many feet are there in $quest miles? EOF $ans = 5280*$quest; print $query->textfield('stu_ans','',10,30); print "<P> Is the above answer correct?",$query->submit("Send Answer in For Grading"); print $query->reset; $quest_x = $query->param('quest'); print $query->end_form; $returned_ans = $query->param('stu_ans'); if ( $query->param('stu_ans') ne '') { print "<em>Student_answer, </em>$returned_ans"; $returned_ans =~ s/\//gi; $returned_ans =~ s/\$//gi; $returned_ans =~ s/#//gi; $returned_ans =~ s/~//gi; $stu_ans = eval($returned_ans); print "<br> student answer = ",$stu_ans; print "<br>, and ans = ",$ans; $criterion = ($stu_ans - $ans)**2; print "<br> criterion = ",$criterion; if ( (($stu_ans - $ans)**2 ) >= 0.01 ) {print "<em>, was WRONG!</EM> <IMG SRC=../icons/checkno.gif>"} else {print "<em>, was RIGHT! </EM> <IMG SRC=../icons/check.gif>"}; }; print $query->end_html;Click Here to see this Random Numbers in Question Example.
There are two points to make here. The first is the rounding of the random number. The code:
$quest = 10.0*rand();#CREATE RANDOM VALUES $quest = int(1000*$quest)/1000;#ROUND APPROPRIATELYchooses a random number between 0 and 10, and then truncates it to 4 significant figures.
The second hard point is the hidden fields problem. We need to know whether or not this particular Perl program has been called before, and to do that we check whether or not the hidden field has a value. If it doesn't have a value, then this is the first time that the Perl program has been called, and we need to assign a value to the hidden field. The line:
if($query->param('quest') eq ""){$query->param('quest',$quest);}accomplishes this. The line:
print $query->hidden('quest');#THEN HIDE IThides it so that between form calls, it is maintained. Then, the line:
$quest = $query->param('quest');#RETREIVE ITassigns this hidden value to a Perl variable for future use.
That's all there is, there isn't any more, Doc.