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.\n";

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 ...

Get Sams Teach Yourself Perl in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.