×
Home About Us Products Services News Free Scripts Contact
news php scripts and software

Perl example - List of Perl pattern match variables


Perl - List of Perl pattern match variables

Parentheses not only serve to 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 used in the replacement expression of a substitution and anywhere else you might want to use them 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.

Category: Perl

 
<< Go back