Pattern Matching Operators and Expressions

Let me first start with a quick overview of the regular expression information I've already covered. To construct patterns that search a variable for a particular expression, you use two operators: the regular expression operator m// and the pattern-match operator =~, like this:

if ($string =~ m/foo/) {
   # do something...
}

As you know, that test simply checks whether the variable $string contains foo.

For these sorts of patterns, the m is optional and can be left off (and usually is). In addition, you can leave off the variable and the =~ if you want to search the contents of the default variable $_. Commonly in Perl, you'll see shorthand pattern matching like this one:

if (/^\d+/) { # ...

Which ...

Get Sams Teach Yourself Perl in 21 Days, Second 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.