Another Example: More Cookies

Let's make a simple modification to the cookie.pl script from yesterday to use pattern matching. Listing 2.2 shows cookie.pl, to refresh your memory:

Listing 2.2. The cookie.pl Script
1: #!/usr/local/bin/perl -w
2: #
3: # Cookie Monster
4:
5: $cookie = "";
6:
7: while ( $cookie ne 'cookie') {
8:   print 'Give me a cookie: ';
9:   chomp($cookie = <STDIN>);
10: }
11:
12: print "Mmmm. Cookie.
";

Line 7 is the important line we're interested in here. The test in line 7 includes the string comparison test ne (not equals), so that each time the $cookie variable does not include the string cookie, the loop will repeat. (We'll look at this kind of loop in a little more detail tomorrow and at all kinds of loops on Day 6).

When you run this example, you have to type the string “cookie” exactly to get out of it. Typing anything else will just repeat the loop.

A useful modification, then, would be to allow the user to type something that contains the word “cookie”—for example, “cookies,” or “here's a cookie, now shut up,” or any other phrase.

All we need to do is modify that one line, line 7, and change the ne comparison to a pattern match and the string to a pattern, like this:

while ( $cookie !~ /cookie/i) {

Why are we using the !~ pattern matching operator, rather than =~? We need a negated comparison here; one that returns true if the comparison does not work. Just as the original nest was a negated comparison (ne, a not-equals string test), we need a negated pattern match here.

The pattern here is simply the string cookie. Note that in simple patterns like this one you don't need the quotes around the string, and note also I am not using the m part of the pattern operator (as I mentioned in the previous section, it's very commonly omitted). I've also included the i option at the end of the pattern so that the cookie won't be case sensitive—the user can type cookie or Cookie or COOKIE and that will be okay.

Listing 2.3 shows the final script, which I've called cookie2.pl:

Listing 2.3. The cookie2.pl Script
#!/usr/local/bin/perl -w

$cookie = "";

while ( $cookie !~ /cookie/i) {
  print 'Give me a cookie: ';
  chomp($cookie = <STDIN>);
}

print "Mmmm.  Cookie.
";
					

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset