Presenting Mathematical Concepts on the World Wide Web
Forms & Scripts

Perl: 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
Back: Program Control
Up: Forms & Scripts


Presenting Mathematical Concepts on the World Wide Web. Copyright © 1997 by Carol Scheftic. All rights reserved. (This section was originally copyrighted in 1996 by The Geometry Center and is re-used here with permission.) Please send comments on this page, or requests for permission to re-use material from this page, to: scheftic@geom.umn.edu
Page established 1-Jun-97; last updated Thursday, 24-Jul-1997 01:22:50 CDT.