#!/usr/bin/perl -wT use strict; use CGI qw( :standard ); use CGI::Carp qw( fatalsToBrowser ); # use CGI # print "Content-type: text/html\n\n"; print header,start_html(); # When I read this I assumed these variables would be # the text of the question but they are the text # of the answers, but as you see later you don't need them. =head1 my ( $question_one, $question_two, $question_three, $question_four, $question_five, $question_six, $question_seven, $question_eight, $question_nine, $question_ten ); =cut # These you don't need yet; #my $total = 10; #my $score; #my $final_score; # If you use leading zeros in the names they sort # and loop naturally ie Q01, Q02, Q03 # You have the answers in the parameter hash so no # need to copy them =head1 $question_one = param( "Q1" ); $question_two = param( "Q2" ); $question_three = param( "Q3" ); $question_four = param( "Q4" ); $question_five = param( "Q5" ); $question_six = param( "Q6" ); $question_seven = param( "Q7" ); $question_eight = param( "Q8" ); $question_nine = param( "Q9" ); $question_ten = param( "Q10" ); =cut # The correct answers I would put in a DATA block at the end # and read them in here but there are lots of formats # you could use my %correct = (); while (){ chomp; my $id = substr($_,0,3); my $value = substr($_,4); $correct{$id} = $value; } # It's easy now to loop around the # questions checking the answers # and updating the score my $total = 0; my $score = 0; foreach (sort keys %correct){ my $answer = param($_) || "" ; # The || gives it defaults, and my $correct = $correct{$_} ; # using temp variables make it easier to read # marking my $result; if ($answer eq $correct){ $result = qq(Correct); ++$score; } else { # It's nice to know what the correct answer was $result = qq(Incorrect The Correct answer was $correct); } # use qq to avoid all those \'s print qq[$_ ). You answered : $answer $result
\n ]; # use [ because of ) in text ++$total; } # work out the % marking to 1 decimal place my $mark = 100 * $score / $total unless $total == 0; # avoid div by zero error $mark = sprintf "%.1f",$mark; # use the cgi module and # since you have a table you can # use 2 columns to make it look neat print table ( Tr( td ("Total questions"), td ($total) ), Tr( td ("Correct"), td ($score) ), Tr( td ("% Score"), td ($mark) ) ); print end_html(); __DATA__ Q01 Larry Wall Q02 Unix administrators Q03 Text processing Q04 Glue Q05 Operating system utilities and services Q06 True Q07 Regular expressions Q08 Open source Q09 TCL Q10 Marc Andreessen