Answers to Chapter 8 Exercises
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>afteras it should, you’ve chosen a hard way to do it.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.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
\bword-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.”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"; } }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 ...