Приглашаем посетить
Гаршин (garshin.lit-info.ru)

Section A.6.  Answers to Chapter 7 Exercises

Previous
Table of Contents
Next

A.6. Answers to Chapter 7 Exercises

  1. Here's one way to do it:

        while (<>) {
          if (/fred/) {
            print;
          }
        }
    

    This is pretty simple. The more important part of this exercise is trying it out on the sample strings. It doesn't match Fred, showing that regular expressions are case-sensitive. (We'll see how to change that later.) It does match frederick and Alfred since both of those strings contain the four-letter string fred. (Matching whole words only, so frederick and Alfred won't match, is another feature we'll see later.)

  2. Here's one way to do it: Change the pattern used in the first exercise's answer to /[fF]red/. You could also have tried /(f|F)red/ or /fred|Fred/, but the character class is more efficient.

  3. Here's one way to do it: Change the pattern used in the first exercise's answer to /\./. The backslash is needed because the dot is a metacharacter, or you could use a character class: /[.]/.

  4. Here's one way to do it: Change the pattern used in the first exercise's answer to /[A-Z][a-z]+/.

  5. Here's one way to do it:

        while (<>) {
          if (/wilma/) {
            if (/fred/) {
              print;
            }
          }
        }
    

    This tests /fred/ after we find /wilma/ matches, but fred could appear before or after wilma in the line; each test is independent of the other.

    If you wanted to avoid the extra nested if test, you might have written something like this:[*]

    [*] Folks who know about the logical-and operator (see Chapter 10), could do both tests of /fred/ and /wilma/ in the same if conditional. That's more efficient and scalable and an all-around better way than the ones given here. But we haven't seen logical-and yet.

        while (<>) {
          if (/wilma.*fred|fred.*wilma/) {
            print;
          }
        }
    

    This works because we'll either have wilma before fred or fred before wilma. If we had written /wilma.*fred/, that wouldn't have matched a line like fred and wilma flintstone though that line mentions them both.

    We made this an extra-credit exercise because many folks have a mental block here. We showed you an "or" operation (with the vertical bar, |), but we never showed you an "and" operation. That's because there isn't one in regular expressions.[Section A.6.  Answers to Chapter 7 Exercises] If you want to know if two patterns are both successful, just test both of them.

    [Section A.6.  Answers to Chapter 7 Exercises] There are some tricky and advanced ways of doing what some folks would call an "and" operation. These are generally less efficient than using Perl's logical-and depending upon what optimizations Perl and its regular expression engine can make.

    Previous
    Table of Contents
    Next