Skip to Main Content
Learning Perl, 5th Edition
book

Learning Perl, 5th Edition

by Randal L. Schwartz, Tom Phoenix, brian d foy
June 2008
Beginner content levelBeginner
352 pages
11h 16m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 5th Edition

Answers to Chapter 8 Exercises

  1. There’s one easy way to do it, and we showed it back in the chapter body. But 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/

    (Of course, 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, although 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. This exercise answer is the same as the previous exercise with a slightly different regular expression:

    #!/usr/bin/perl
    
    use 5.010;
    
    while (<STDIN>) {
      chomp;
      if (/(?<word>\b\w*a\b)/) {
        print "Matched: |$`<$&>$'|\n";
        print "'word' contains '$+{word}'\n";       # The new output line
      } else {
        print "No match: |$_|\n";
      }
    }
  5. 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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Perl, 6th Edition

Learning Perl, 6th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Beginning Perl

Beginning Perl

Curtis Ovid Poe
Learning Perl 6

Learning Perl 6

brian d foy
Mastering Perl

Mastering Perl

brian d foy

Publisher Resources

ISBN: 9780596520106Supplemental ContentErrata Page