First off, always use strictures (use strict; use warnings;).
The major problem is that the questions are embedded in the code. That makes the code incredibly fragile and horrific to maintain. Move your questions out into a data structure, or better still a file (then build the data structure). Consider:
use strict; use warnings; #variable initialization my @questions = ( {question => "Question #1: Who is buried in Grant's tomb?", answers => [ "Grant", "Lincoln", "Frank", "None of the above.", ], answer => 'a', }, ); my $wrong_count = 0; for my $question (@questions) { printQuestion ($question); print "\nThe answer is: "; $question->{reply} = lc <STDIN>; chomp $question->{reply}; if ($question->{reply} eq $question->{answer}) { print "Correct\n\n"; next; } ++$wrong_count; } print "\n\n"; exit if ! $wrong_count; print "Correct answers:\n\n"; for my $question (@questions) { my $reply = ord ($question->{reply}) - ord ('a'); my $ans = ord ($question->{answer}) - ord ('a'); next if $reply == $ans; printQuestion ($question); print "\nThe answer is: $question->{answers}[$ans]\n"; if ($reply > @{$question->{answers}}) { print "You didn't give a valid answer\n" } else { print "Your answer was: $question->{answers}[$reply]\n"; } print "\n"; } sub printQuestion { my ($question) = @_; my $letter = 'A'; print "$question->{question}\n"; for my $answer (@{$question->{answers}}) { print "$letter: $answer\n"; ++$letter; } }
In reply to Re: Best code approach for this goal
by GrandFather
in thread Best code approach for this goal
by irvson
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |