in reply to Chemistry Elements Quiz

I like Chemistry.

In my experience, the best way to get rid of repetitive almost-the-same things, like the loops you have, is usually found in a hash. Here's my suggestion. I'm also interested in any comments or suggestions.


#!/usr/bin/perl -w use strict; use Chemistry::Elements qw/get_name get_Z get_symbol/; my $test_type = shift || ''; print "ChemTest. Testing your knowledge of the Periodic Table.\n"; print "Test by name, number or symbol\n"; die "\n\tUsage: $0 [name|number|symbol]\n\n" if $test_type !~ /name|number|symbol/; print "Testing by $test_type\n"; print "Enter 'quit' at any prompt to quit.\n"; while(1){ my $number = int(rand 109) + 1; my $name = &get_name($number); my $symbol = &get_symbol($number); my %element = ( 'number' => $number, 'name' => $name, 'symbol' => $symbol ); my $given = $element{$test_type}; print "\nElement $test_type is $given\n"; delete $element{$test_type}; foreach my $answer(keys %element ){ print "Enter the $answer: "; chomp (my $guess = <STDIN>); die "Thanks for playing\n" if $guess eq "quit"; if ($guess eq $element{$answer}) { print "Correct. "; } else { print "Incorrect. "; } print "$element{$answer} is the $answer for $given\n"; } }

Replies are listed 'Best First'.
Re: Re: Chemistry Elements Quiz
by cjf (Parson) on May 24, 2002 at 13:46 UTC

    Exactly what I was looking for. Thanks :)

Re: Re: Chemistry Elements Quiz
by OxYgEn (Acolyte) on Mar 01, 2004 at 02:40 UTC
    Can't locate Chemistry/ in @INC (@INC contains: C:/Perl/lib C:/Perl/site/lib .) at line 5.
    BEGIN failed--compilation aborted at line 5.