Here's one more example, just for fun. Back in the days of text-only computer terminals, there was a practical-joke program that floated around for a while called “the cookie monster.” The cookie monster program would lock up your terminal and endlessly prompt you to “Give me a cookie.” (or, “I WANT A COOKIE.” or some variation), and no matter what you typed, it would always insist it wanted a cookie. The only way out of the program was to actually type cookie, something that only seemed obvious after you had spent an hour trying to get out of the program.
Listing 1.3 shows a simple Perl version of the cookie monster program.
This one's slightly more complicated than either Hello World or Echo. Here's a sample of what it looks like when you run it:
% cookie.pl Give me a cookie: asdf Give me a cookie: exit Give me a cookie: quit Give me a cookie: stop Give me a cookie: I mean it Give me a cookie: @*&#@(*&@$ Give me a cookie: cookie Mmmm. Cookie. %
Note
That last line is a bit of a variation on the traditional cookie monster program. Note also that this one is pretty easy to get out of; a simple Ctrl+C will break right out of it. The original program was not nearly so nice. But hey, it's only Day One; we can't get that sophisticated yet.
Here's what is going on in the Cookie script, line by line:
Line 2 and 3 are comments (you should be able to figure that out by now).
Line 5 initializes the $cookie variable to be the empty string "".
Line 7 is the start of a while loop. As long as the test inside the parentheses is true, the code inside the curly braces will be executed. Here, the test is to see if the $cookie variable does not contain the word cookie. You'll learn more about while and other loops on Day 4, “Conditionals and Loops.”
Line 8 prompts for the cookie. Note that there's no newline character at the end.
Line 9 looks really weird. The chomp function, which you'll learn more about tomorrow, simply strips the newline (return) character off the end of whatever it was you typed (and stored in the $cookie variable).
Once again, if you don't understand every line, don't panic. This is the gentle tour. All will become clear to you tomorrow.