#!/usr/bin/perl -w use strict; # # Use uppercase for the city names to make it easier to compare the # user's answers. For the country names, it just makes it easier for # the user to find the relevant part of the question. # my %capitals = ("UNITED STATES OF AMERICA" => "WASHINGTON", "RUSSIA" => "MOSCOW", "INDIA" => "NEW DELHI", "CHINA" => "BEIJING"); my @countries = keys %capitals; # # We start off with $asked set to -1 because when they type 'QUIT' it # will be one higher than we would like, since that question should # not be counted. # # I am setting $answer to "" because as of the time when this was # assigned, "last" had not yet been taught. A better way to do this # is to use an infinite loop ("while(1)") and use "last" when they # type "QUIT". This way, the test for "QUIT" would not need to appear # more than once. Think what might happen if the exit command was # changed from "QUIT" to "EXIT"? You would have to modify two places, # and if you didn't notice that you might cause a bug. # my $answer = ""; my $asked = -1; my $correct = 0; while(uc $answer ne 'QUIT') { # # Since rand(4) generates a number between 0 and 3.999999..., using # int() makes it in the range 0 to 3, inclusive. # my $i = int(rand(@countries)); # # Ask the question # my $country = $countries[$i]; print "What is the capital of $country? "; chomp($answer = ); $asked++; # # Check the answer # if (uc $answer eq $capitals{$country}) { print "That is correct!\n"; $correct++; } elsif (uc $answer ne 'QUIT') { print "Sorry, that is incorrect.\n"; } } # # Compute and display score. # my $pct = int($correct * 100 / $asked); print("Thank you for playing! ", "You got $correct out of $asked right ($pct%).\n");