< Day Day Up > |
Now that you have an easy way to keep data on the disk, it's time to put it to good use. This exercise presents a free-form memo pad that keeps information based on keys and allows you to search and retrieve that information with simple queries. A sample session with the program (called memopad ) is shown in Listing 15.1. To query the memopad program, simply type the name of a topic, followed by a question mark. To program in a new fact, type a phrase in the form " X is Y ", where X is the topic and Y is the information to associate with that topic. You can search the database for similarities by typing "like pattern ?" where pattern is a regular expression to search for in the topics. All topics matching that expression will be printed. To exit the program, type quit at the prompt. Listing 15.1. Sample Session with memopadYour question: perl? I don't know about "perl" Your question: perl is a programming language Ok, I'll remember "perl" as "a programming language" Your question: perl's homepage is at http://www.perl.org Ok, I'll remember "perl's homepage" as "at http://www.perl.org" Your question: perl? perl is a programming language Your question: like perl? perl is like perl perl's homepage is like perl Your question: quit All the information given to the memopad program will be remembered each time the program is run, because the data is stored in a hash tied to a DBM file. The code for memopad is shown in Listing 15.2. Listing 15.2. Full Listing of memopad1: #!/usr/bin/perl -w 2: use strict; 3: 4: my(%answers, $subject, $info, $pattern); 5: 6: dbmopen(%answers, "answers", 0666) die "Cannot open answer DBM: $!"; 7: while(1) { 8: print "Your question ('quit' to quit): "; 9: chomp($_=lc(<STDIN>)); 10: last if (/^quit$/); 11: if (/like\s+(.*)\?/) { 12: $pattern=; 13: while( ($subject,$info)=each(%answers) ) { 14: if ($subject=~/$pattern/) { 15: print "$subject is like $pattern\n"; 16: } 17: } 18: } elsif (/(.*)\?/) { 19: $subject=; 20: if ($answers{$subject}) { 21: print "$subject is $answers{$subject}\n"; 22: } else { 23: print qq{I don't know about "$subject"\n}; 24: } 25: } elsif (/(.*)\sis\s(.*)/) { 26: $subject=; 27: $info=; 28: $answers{$subject}=$info; 29: print qq{Ok, I'll remember "$subject" as "$info"\n}; 30: } else { 31: print "I'm sorry, I don't understand.\n"; 32: } 33: } 34: dbmclose(%answers);
|
< Day Day Up > |