Answers to Chapter 7 Exercises
Here’s one way to do it:
while (<>) { if (/fred/) { print; } }
This is pretty simple. The more important part of this exercise is trying it out on the sample strings. It doesn’t match
Fred
, showing that regular expressions are case-sensitive. (We’ll see how to change that later.) It does matchfrederick
andAlfred
since both of those strings contain the four-letter stringfred
. (Matching whole words only, sofrederick
andAlfred
won’t match, is another feature we’ll see later.)Here’s one way to do it: Change the pattern used in the first exercise’s answer to
/[fF]red/
. You could also have tried/(f|F)red/
or/fred|Fred/
, but the character class is more efficient.Here’s one way to do it: Change the pattern used in the first exercise’s answer to
/\./
. The backslash is needed because the dot is a metacharacter, or you could use a character class:/[.]/
.Here’s one way to do it: Change the pattern used in the first exercise’s answer to
/[A-Z][a-z]+/
.Here’s one way to do it:
while (<>) { if (/wilma/) { if (/fred/) { print; } } }
This tests
/fred/
after we find/wilma/
matches, butfred
could appear before or afterwilma
in the line; each test is independent of the other.If you wanted to avoid the extra nested
if
test, you might have written something like this:[371]while (<>) { if (/wilma.*fred|fred.*wilma/) { print; } }
This works because we’ll either have
wilma
beforefred
orfred
beforewilma
. If we had written/wilma.*fred/
, that wouldn’t have matched ...
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.