O'Reilly logo

Learning Perl, Fourth Edition by brian d foy, Tom Phoenix, Randal L. Schwartz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required