Category: | Miscellaneous |
Author/Contact Info | /msg cjf |
Description: | Simple command line quiz using Chemistry::Elements. Provides you with either the element name, symbol, or atomic number and asks you for the other two. All suggestions (especially those dealing with the 3 repetitive subs) are greatly appreciated. |
#!/usr/bin/perl -w use strict; use Chemistry::Elements qw/get_name get_Z get_symbol/; my $test_type = shift || ""; my %tests = ( name => \&name_test, number => \&number_test, symbol => \&symbol_test, ); if (exists $tests{$test_type}) { $tests{$test_type}->(); } else { error("Invalid Test type. Choose 'name', 'number', or 'symbol'."); } sub name_test { while (1) { my $number = int(rand 109) + 1; my $symbol = get_symbol($number); my $name = get_name($number); print "Element name = $name\n"; print "Enter symbol: "; chomp (my $ans_symbol = <STDIN>); if (lc($ans_symbol) eq lc($symbol)) { print "Correct. $symbol is the atomic symbol for $name\n"; } else { print "Incorrect. $symbol is the atomic symbol for $name\n +"; } print "Enter $name\'s atomic number: "; chomp (my $ans_number = <STDIN>); if ($ans_number eq $number) { print "Correct. The atomic number for $name is $number\n"; } else { print "Incorrect. The atomic number for $name is $number\n +"; } print "\n"; } } sub number_test { while (1) { my $number = int(rand 109) + 1; my $symbol = get_symbol($number); my $name = get_name($number); print "Atomic number = $number\n"; print "Enter symbol: "; chomp (my $ans_symbol = <STDIN>); if (lc($ans_symbol) eq lc($symbol)) { print "Correct. $symbol has the atomic number $number\n"; } else { print "Incorrect. $symbol has the atomic number $number\n" +; } print "Which element has the atomic number $number: "; chomp (my $ans_name = <STDIN>); if (lc($ans_name) eq lc($name)) { print "Correct. $number is the atomic number for $name\n"; } else { print "Incorrect. $number is the atomic number for $name\n +"; } print "\n"; } } sub symbol_test { while (1) { my $number = int(rand 109) + 1; my $symbol = get_symbol($number); my $name = get_name($number); print "Element symbol = $symbol\n"; print "Enter Name: "; chomp (my $ans_name = <STDIN>); if (lc($ans_name) eq lc($name)) { print "Correct. $symbol is the symbol for $name\n"; } else { print "Incorrect. $symbol is the symbol for $name\n"; } print "Enter $symbol\'s atomic number: "; chomp (my $ans_number = <STDIN>); if ($ans_number eq $number) { print "Correct. $symbol\'s atomic number is $number\n"; } else { print "Incorrect. $symbol\'s atomic number is $number\n"; } print "\n"; } } sub error { my $error = shift; print "Error: $error\n"; exit; } |
Back to
Code Catacombs