Документация
HTML CSS PHP PERL другое

Section A.7.  Answers to Chapter 8 Exercises

 
Previous
Table of Contents
Next

A.7. Answers to Chapter 8 Exercises

  1. There's one easy way to do it, and we showed it back in the chapter body. If your output isn't saying before<match>after as it should, you've chosen a hard way to do it.

  2. Here's one way to do it:

        /a\b/
    

    (That's a pattern for use inside the pattern test program.) If your pattern mistakenly matches barney, you probably needed the word-boundary anchor.

  3. Here's one way to do it:

        #!/usr/bin/perl
        while (<STDIN>) {
          chomp;
          if (/(\b\w*a\b)/) {
            print "Matched: |$`<$&>$'|\n";
            print "\$1 contains '$1'\n";       # The new output line
          } else {
            print "No match: |$_|\n";
          }
        }
    

    This is the same test program (with a new pattern), except that the one marked line has been added to print out $1.

    The pattern uses a pair of \b word-boundary anchors[*] inside the parentheses though the pattern works the same way when they are placed outside. That's because anchors correspond to a place in the string but not to any characters in the string: anchors have "zero width."

    [*] Admittedly, the first anchor isn't really needed due to details about greediness that we won't go into here. It may help efficiency. It certainly helps with clarity, and in the end, that one wins out.

  4. Here's one way to do it:

        m!
          (\b\w*a\b)       # $1: a word ending in a
          (.{0,5})         # $2: up to five characters following
        !xs                # /x and /s modifiers
    

    (Don't forget to add code to display $2 now that you have two memory variables. If you change the pattern to have just one again, you can simply comment out the extra line.) If your pattern doesn't match wilma anymore, perhaps you require one or more characters instead of zero or more. You may have omitted the /s modifier since there shouldn't be newlines in the data. (If there are newlines in the data, the /s modifier could make for different output.)

  5. Here's one way to do it:

        while (<>) {
          chomp;
          if (/\s+$/) {
            print "$_#\n";
          }
        }
    

    We used the pound sign (#) as the marker character.

    Previous
    Table of Contents
    Next
    © 2000- NIV