Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Chemistry Elements Quiz

by mrbbking (Hermit)
on May 24, 2002 at 13:37 UTC ( #169057=note: print w/ replies, xml ) Need Help??


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.

Changes:

  • Added more graceful way to exit.
  • Made the tests case-sensitive (because element symbols are case-sensitive. May be too strict, then, for element names, but maybe not. Depends on your teacher.. :-)
  • Removed three loops, replacing them with one.
#!/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"; } }


Comment on Re: Chemistry Elements Quiz
Download Code
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
    C:\>perl chemquiz.pl
    Can't locate Chemistry/Elements.pm in @INC (@INC contains: C:/Perl/lib C:/Perl/site/lib .) at chemquiz.pl line 5.
    BEGIN failed--compilation aborted at chemquiz.pl line 5.

    C:\>

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://169057]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (8)
As of 2014-07-10 08:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (202 votes), past polls