Perl Notes


Chapter 17 Pattern Matching & Regular Expressions

The match operator checks to see of a variable contains the specified data. Then you can setup a conditional statement to do something if the data's there or if it is not.

Perl Regular Expressions

.Matches any character except newline
[a-z0-9]Matches any single character of set
[^a-z0-9]Matches any single character not in set
\dMatches a digit, same as [0-9]
\DMatches a non-digita, same as [^0-9]
\wMatches an alphanumeric (word) character [a-zA-Z0-9]
\WMatches a non-word character [^a-zA-Z0-9]
\sMatches a whitespar characteer (space, tab, newline)
\SMatches a non-whitespace character
\nMatches a newline
\rMatches a return
\tMatches a tab
\fMatches a formfeed
\bMatches a backspace (inside [ ] only)
\0Matches a null character
\000Also matches a null character becasue...
\nnnMatches an ASCII character of that octal value
\cXMatches an ASCII control character
\metacharMatches the character itself (\|, \., \*...)
(abc)Remembers the match for later backreference
\1Matches whatever first of parens matched
\2Matches whatever second set of parens matched
\3and so on...
x?Matches 0 or 1 x's, where x is any of above
x*Matches 0 or more x's
x+Matches 1 or more x's
x{m}Matches at exactly m x's
x{m,}Matches at least m x's
x{m, n}Matches at least m x's but no more than n
abcMatches all of a, b, and c in order
fee|fie|foeMatches one of fee, fie or foe
\bMatches a word boundry (outside [ ] only)
\BMatches a non-word boundry
^Anchors match to the beginning of a line or string
$Anchors match to the end of a line or string

Here's some examples:

  $string="Perl Rocks";

  if ($string =~ /e/) {
    print "string contains an e.\n";
  } else {
    print "string does NOT contain an e.\n";

  if ($string =~ /\w+/) {
    print "string contains two word characters.\n";
  } else {
    print "string does NOT contain two word characters.\n";

  if ($string !~ /e/) {
    print "string does NOT contain an e.\n";
  } else {
    print "string contains an e.\n";


eEvaluate the right side as an expression.
gMatch globally, i.e. all occurrences.
iCase-insensitive pattern matching.
mTreat string as multiple lines.
oOnly compile pattern once, even if variables within it change.
sTreat string as single line.
xUse extended regular expressions
$+the last pattern that was matched (useful when there are alternatives)
$&the matched string
$`everything before the matched string
$'everything after the matched string

  $string="Helllo Baby!";
  $string =~ s/lll/ll/g;