Chapter 9. Using Regular Expressions
Now that we’ve seen what goes inside a regular expression, let’s take what we’ve learned back into Perl.
Matches with m//
We’ve been writing patterns in pairs of forward slashes, like
/fred/
. But this is actually a shortcut for the
m//
(pattern match) operator. As we saw
with the qw//
operator, you may choose any pair of
delimiters to quote the contents. So, we could write that same
expression as m(fred)
,
m<fred>
, m{fred}
, or
m[fred]
using those paired delimiters, or as
m,fred,
, m!fred!
,
m^fred^
, or many other ways using nonpaired
delimiters.[1]
The shortcut is that if you choose the forward slash as the
delimiter, you may omit the initial m
. Since Perl
folks love to avoid typing extra characters, you’ll see most
pattern matches written using
slashes, as in
/fred/
.
Of course, you should wisely choose a delimiter that doesn’t
appear in your pattern.[2] If you wanted to make a pattern to match the beginning of
an ordinary web URL, you might start to write
/^http:\/\//
to match the initial
"http://"
. But that’s easier to read, write,
maintain, and debug if you use a better choice of delimiter:
m%^http://%
.[3]
It’s common to use curly braces as the delimiter. If you use a programmers’ text editor, it probably has the ability to jump from an opening curly brace to the corresponding closing one, which can be handy in maintaining code.
Option Modifiers
There are several option modifier letters, sometimes called flags , which may be appended as a ...
Get Learning Perl, 3rd 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.