Using Simple Patterns
To match a pattern (regular expression) against the contents
of $_
, simply put the pattern between
a pair of forward slashes (/
),
like we do here:
$_ = "yabba dabba doo"; if (/abba/) { print "It matched!\n"; }
The expression /abba/
looks for
that four-letter string in $_
; if it
finds it, it returns a true value. In this case, it’s found more than
once, but that doesn’t make any difference. If it’s found at all, it’s a
match; if it’s not in there at all, it fails.
Because the pattern match is generally being used to return a true
or false value, it is almost always found in the conditional expression
of if
or while
.
All of the usual backslash escapes that you can put into
double-quoted strings are available in patterns, so you could use the
pattern /coke\tsprite/
to match the
11 characters of coke
, a tab, and
sprite
.
About Metacharacters
Of course, if patterns matched only simple literal strings, they wouldn’t be very useful. That’s why there are a number of special characters, called metacharacters, that have special meanings in regular expressions.
For example, the dot (.
) is a wildcard
character—it matches any single character except a newline (which is
represented by "\n"
). So, the
pattern /bet.y/
would match
betty
. Or it would match betsy
, or bet=y
, or bet.y
, or any other string that has bet
, followed by any one character (except a
newline), followed by y
. It
wouldn’t match bety
or betsey
, though, since those don’t have
exactly one character between the t
and ...
Get Learning Perl, 5th 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.