Oct 212013
 
Article Perl

The $<digit> and $+ variables

When expressions enclosed in parentheses appear inside a regular expresion, the matching substrings are assigned to the special variables $1, $2, $3,… up to $9.

$+ is the special variable that represent the substring matching the last expression enclosed in parentheses.

For instance:

These sample sentences produce the following output:

The $, $& and $' variables

The $& variable holds the last match found when a regular expression has been evaluated.

The $ (dollar-backtick) variable holds the substring preceding the matched string (prematch)

The $’ (dollar-apostrophe) variable holds the substring after the matched string (postmatch).

The sample code below:

generates the following output:

The ${^MATCH}, ${^PREMATCH} and ${^POSTMATCH} variables

Due to the way the perl interpreter has been implemented, the use of the variables $`, $& and $’ anywhere in a script causes a noticeable degradation in performance in the processing of all the regular expressions in it.

This problem can be avoided replacing those variables with the variables ${^MATCH}, ${^PREMATCH} and ${^POSTMATCH}, and adding the  “/p” modifier to the regular expression. The previous example could be rewritten as:

THe @- and @+ variables

The @- y @+ arrays hold the indexes to the beginning and end of each of the matching substrings in a regular expression.

@-[0] y @+[0] are the indexes of the substring matching the full regular expression. The next entries hold the indexes for the first, second, etc. subexpressions inside the regular expression.

For instance, the following sample code:

Produces as output:

The %+ and %- variables

In a regular expression, it is possible to assign a name to a subexpression enclosed in parentheses (…). This is done using the syntax (?<name>…).

The %+ hash variable gives access to each of the matching substrings of named subexpressions.

Example:

The %- variable works like %+, but the values in it are arrays. Each of these arrays holds all the matching substrings for the same named subexpression.

Example:

The $^N variable

This special variable holds the matching substring for the last subexpression  in parentheses processed, and is mainly used inside a regular expresion, in subexpressions like (?{ $variable = $^N}) to assign the string to a variable

Example:

In the example above, the result of evaluating the first subexpression “([^ ]*)” is assigned to the variable”$word”.

Index of posts related to Perl programming

 Posted by at 2:23 pm

 Leave a Reply

(required)

(required)