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[373] 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.”

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

Get Learning Perl, Fourth 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.