Next: Subroutines
Up: CGI Scripts with Perl
Prev: Program Control

Pattern Matching

One of Perl's real strengths is it's pattern matching capability. The most basic syntax is illustrated here:
$w = "The wings of desire bore Adrian ever higher over the darkling
abyss of life as a scullery lad.";

if ($w =~ /abyss/) {
   print "Too romantic! \n";
}

($w =~ /bore/) && print "Put some life into it! \n";

Regular Expressions

The object between the slashes specifying the pattern to match is called a regular expression. Here are a few simple examples illustrating regular expressions.

"This is a test" =~ /T..s/;    # matches 'This'

"This is a test" =~ /T.*s/;    # matches 'This is a tes'

"This is a test" =~ /s[^\s]/   # matches 'st'

Substitution

Instead of simple matching, Perl allows for substitution as well. The basic syntax is:
$x = s/reg expr/thing to substitute/
This is particularly useful when used in conjunction with parentheses. If you include a pair of parentheses in a regular expression, the sub-expression that matches the regular expression they enclosed is stored in a variable called $1. If you have two pairs, the matches are stored in $1 and $2, etc.
$w = "This is a mistake dyslexic";

$w =~ s/(mistake) (dyslexic)/$2 $1 \n/;

print $w;


Next: Subroutines
Up: CGI Scripts with Perl
Prev: Program Control

[HOME] The Geometry Center Home Page

Comments to: webmaster@geom.umn.edu
Created: May 07 1996 --- Last modified: May 29 1996