Pattern Match Variables

Parentheses not only group elements in a regular expression, they also remember the patterns they match. Every match from a parenthesized element is saved to a special, read-only variable indicated by a number. You can recall and reuse a match by using these variables.

Within a pattern, each parenthesized element saves its match to a numbered variable, in order starting with 1. You can recall these matches within the expression by using \1, \2, and so on.

Outside of the matching pattern, the matched variables are recalled with the usual dollar sign, i.e., $1, $2, etc. The dollar sign notation should be used in the replacement expression of a substitution and anywhere else you might want to use the variables in your program. For example, to implement “i before e, except after c”:

s/([^c])ei/$1ie/g;

The backreferencing variables are:

$+

Returns the last parenthesized pattern match

$&

Returns the entire matched string

$'

Returns everything before the matched string

$'

Returns everything after the matched string

Backreferencing with these variables will slow down your program noticeably for all regular expressions.

Get Perl in a Nutshell, 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.