Chapter 6. Pattern Matching


[Art is] pattern informed by sensibility.

Sir Herbert Read, The Meaning of Art

Although most modern programming languages offer primitive pattern matching tools, usually through an extra library, Perl’s patterns are integrated directly into the language core. Perl’s patterns boast features not found in pattern matching in other languages, 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 punctuation-intensive language of regular expressions,[8] provide access to powerful algorithms normally available only to computer science scholars.

“If this pattern matching thing is so powerful and so fantastic,” you may be saying, “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 used 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 ingrained 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 ...

Get Perl Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.