Answers to Chapter 8 Exercises
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>afteras it should, you’ve chosen a hard way to do it.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.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[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.”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
$2now 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 matchwilmaanymore, perhaps you require one or more characters instead of zero or more. You may have omitted the/smodifier since there shouldn’t be newlines in the data. (If there are newlines ...
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.
Read now
Unlock full access