perl

Page 149

Chapter 9

Regular Expressions 9.1 Introduction Now we are marching into probably the most exciting chapter in this tutorial. Regular expressions (regexps, or even RE) are what makes Perl an ideal language for “practical extraction and reporting”, as the name implies. To give you an idea, let me first give you an overview on how to perform pattern matching in Perl. First, you construct the regular expression, which is essentially a sequence of characters describing the pattern you would like to match. The term “pattern” may seem a little bit foreign to you, but you may actually have had some experience of it already. For example, in MS-DOS if you would like to list all files with the extension .txt (presumably text files), you may issue a command like

dir *.txt On Unix-like operating systems, similarly, you can specify

ls *.txt The “*.txt” here can be described as a pattern as it is the specification used by the operating system (strictly speaking, the shell, i.e. the program in charge of reading commands from you and displaying output) to look for the file entries that have to be displayed. This is a very simple pattern, but Perl provides users with a very powerful set of regular expressions that can be used to specify the patterns, so you can make your search specification more specific. After constructing the regular expression, you can then bind the data to be searched (for example, text files or just a line of user input) to the pattern using the binding operators =∼ or !∼. In this process, you have provided the Perl regexp engine with both the data to search for and the data to be searched. The return value indicates if pattern matching is successful. If it is successful, you may want to store the data temporarily, or in a file, or export the results directly to the standard output. Regular expressions are used in Perl in a number of ways:

?

Search for a string that matches a specified pattern, and optionally replacing the pattern found with some other strings

?

Counting the number of occurrences of a pattern in a string 137


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.