Regular Expression Special Variables

For more information on regular expressions, see Section 4.6 later in this chapter.

$ digit

Contains the text matched by the corresponding set of parentheses in the last pattern matched. For example, $1 matches whatever was contained in the first set of parentheses in the previous regular expression.

$&$MATCH

The string matched by the last successful pattern match.

$`$PREMATCH

The string preceding whatever was matched by the last successful pattern match.

$`$POSTMATCH

The string following whatever was matched by the last successful pattern match.

$+$LAST_PAREN_MATCH

The last bracket matched by the last search pattern. This is useful if you don’t know which of a set of alternative patterns was matched. For example:

/Version: (.*)|Revision: (.*)/ && ($rev = $+);
$^N

The string matched by the most recently closed group. This is most useful inside (?{ . . . }) blocks for examining matched text. If you have multiple matches denoted by parentheses, $^N can be used in lieu of $1, $2, $3, etc., so you don’t have to manually count the number of sets of parentheses that denote your matches. For example:

#!/usr/local/bin/perl -w

$words = "person|here";
$words =~ /(\w+)\|(\w+)/;
print $^N;   # Prints 'here'

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.