Using Simple Patterns

To match a pattern (regular expression) against the contents of $_, put the pattern between a pair of forward slashes (/) as 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 eleven characters of coke, a tab, and sprite.

About Metacharacters

If patterns matched only literal strings, they wouldn’t be very useful. That’s why a number of special characters, called metacharacters , 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. It would also match betsy, bet=y, 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 since those don’t have one character between the t and the y. The dot always matches exactly one character.

If you ...

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.