
BillKSmith
Veteran
Aug 15, 2012, 9:37 AM
Post #2 of 2
(10196 views)
|
Re: [noobiedoobie] Trying to Create Biology Example Program
[In reply to]
|
Can't Post
|
|
Who? amd What? questions need diferent hashes. The following example should get you started.
use strict; use warnings; my %classification = get_rules(); my %who_is; foreach my $animal (keys %classification) { push @{$who_is{$classification{$animal}}}, $animal; } while ( (my $question = prompt('Enter question ("exit" to quit): ')) ne 'exit') { if ($question =~ /^What/){ my $test = join '|', keys %classification; my ($animal) = $question =~ /(:?$test)/; if (!defined $animal) { print "Your animal is not classified.\n"; next; } print "$animal is $classification{$animal}.\n"; } elsif ($question =~ /^Who/) { my $test = join '|', keys %who_is; my ($catagory) = $question =~ /(:?$test)/; if (!defined $catagory) { print "Your catagory is not known.\n"; next; } foreach my $animal (@{$who_is{$catagory}}) { print "$animal is $classification{$animal}.\n"; } } else { print 'Question must start with "Who" or "What".', "\n"; } } sub prompt { print $_[0]; my $response = <>; chomp $response; return $response; } sub get_rules { my %classification; while (my $rule = <DATA>){ my ($animal, $catagory) = $rule =~ /\AAn?\s(\w+)\sis\san?\s(\w+)\.\s*\z/; $classification{$animal} = $catagory; } return %classification; } __DATA__ A cat is a mammal. A dog is a mammal. A bluejay is a bird. A snake is a reptile. A lizard is a reptile. A frog is an amphibian. An owl is a bird. A carp is a fish. Good Luck, Bill
|