next up previous contents
Next: Pattern Precedence Up: Regular Expressions Previous: Quantifiers

Pattern Memory

Matching arbitrary numbers of characters is fine, but without the capability to find out what was matched, patterns would not be very useful. Perl lets you enclose pattern components inside parentheses in order to store the string that matched the components into pattern memory. You also might hear pattern memory referred to as pattern buffers. This memory persists after the match statement is finished executing so that you can assign the matched values to other variables.

You saw a simple example of this earlier right after the component descriptions. That example looked for the first word in a string and stored it into the first buffer, $1. The following small program (mem1.pl):

$_ =  "AAA BBB ccC";
m/(\w+)/;
print("$1\n");

will display

AAA

You can use as many buffers as you need. Each time you add a set of parentheses, another buffer is used. If you want to find all the words in the string, you need to use the /g match option. In order to find all the words, you can use a loop statement that loops until the match operator returns false (mem2.pl).

$_ =  "AAA BBB ccC";

while (m/(\w+)/g) {
    print("$1\n");
}

The program will display

AAA
BBB
ccC

If looping through the matches is not the right approach for your needs, perhaps you need to create an array consisting of the matches (mem3.pl).

$_ =  "AAA BBB ccC";
@matches = m/(\w+)/g;
print("@matches\n");

The program will display:

AAA BBB ccC

Perl also has a few special variables to help you know what matched and what did not. These variables occasionally will save you from having to add parentheses to find information.

Hint If you need to save the value of the matched strings stored in the pattern memory, make sure to assign them to other variables. Pattern memory is local to the enclosing block and lasts only until another match is done.


next up previous contents
Next: Pattern Precedence Up: Regular Expressions Previous: Quantifiers
dave@cs.cf.ac.uk