Chapter 6. Pattern Matching

[Art is] pattern informed by sensibility.

Sir Herbert Read, The Meaning of Art

Introduction

Most modern programming languages offer primitive pattern-matching tools, usually through an extra library. In contrast, Perl’s patterns are integrated directly into the language core. Perl’s pattern matching boasts features not found elsewhere, features that encourage a whole different way of looking at data. Just as chess players see patterns in the board positions that their pieces control, Perl adepts look at data in terms of patterns. These patterns, expressed in the intensely symbolic notation of regular expressions,[1] provide access to powerful algorithms normally available only to scholars of computer science.

“If this pattern matching thing is so powerful and so fantastic,” you may be asking, “why don’t you have a hundred different recipes on regular expressions in this chapter?” Regular expressions are the natural solution to many problems involving numbers, strings, dates, web documents, mail addresses, and almost everything else in this book; we use pattern matching over 100 times in other chapters. This chapter mostly presents recipes in which pattern matching forms part of the questions, not just part of the answers.

Perl’s extensive and integrated support for regular expressions means that you not only have features available that you won’t find in any other language, but you have new ways of using them, too. Programmers new to Perl often look for functions ...

Get Perl Cookbook, 2nd 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.