XML technologies / Regular expressions / Perl / Unusual techniques with Perl regex extensions / local in a code pattern
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
Within a code pattern, local acquires a new meaning. Understanding this requires a solid grasp of dynamic scopes (see Dynamically scoped values) and the breadcrumbs analogy for regex-directed NFA operation under How regex engines work. The following contrived, and flawed, example illustrates it simply. The regex checks whether a line contains only ˹\w+˼ and ˹\s+˼, while counting how many ˹\w+˼ are actually ˹\d+\b˼.
my $Anzahl = 0;
$text =~ m{
^ (?> \d+ (?{ $Anzahl++ }) \b | \w+ | \s+ )* $
}x;Applied to a string such as ›123●abc●73●9271●xyz‹, the regex counts three numbers in $Anzahl. ›123●abc●73xyz‹, however, yields two numbers rather than one. The variable $Anzahl increments as soon as ›73‹ matches, but the following ˹\b˼ cannot match. Backtracking discards the alternative, but backtracking does not reset the counter. Once code in a pattern has executed, backtracking cannot unexecute it.
If the atomic parentheses ˹(?>...)˼ (see Atomic parentheses) seem confusing, they merely prevent interminable matching (see Avoiding interminable matching with atomic groups). They do not affect backtracking within the atomic group, only backtracking beyond the group. Thus, ˹\d+˼ can be undone if the following ˹\b˼ fails.
Here the simple fix is to move ˹\b˼ before the code containing the counter $Anzahl, so it increments only after a real number is found and cannot later be undone. But another solution illustrates the special behavior of local and the use of local within a regex:
our $Anzahl = 0;
$text =~ m{
^ (?> \d+ (?{ local($Anzahl) = $Anzahl + 1 }) \b | \w+ | \s+ )* $
}x;First, $Anzahl changes from a my variable to a global variable. Under use strict, unqualified globals require a declaration with our .
Second, the variable $Anzahl acquires dynamic scope through local. The special behavior of local in a code pattern is: Localizing a variable inside a regex restores its previous value when backtracking undoes the local. Thus, local($Anzahl) = $Anzahl + 1 executes immediately, setting $Anzahl to 2, when ˹\d+˼ matches the two digits ›73‹. But that change is local to the current attempt. If it fails and the engine backtracks before local , it leaves that dynamic scope and $Anzahl regains its previous value, 1, unchanged until a match is found.
Interpolating code patternsFor security, Perl normally forbids interpolating a string variable containing a code pattern
is therefore allowed, but not:
This restriction is deliberate. Existing scripts often turn user input into regexes; allowing arbitrary Perl code through these constructs would create a huge security hole. It is therefore normally forbidden. To allow this interpolation, lift the restriction with
. With other arguments, the pragma Sanitizing user input before interpolation If interpolation is enabled while regexes still include user input, ensure that input contains neither code patterns nor dynamic constructs. Check it with A per-regex or even per-subexpression modifier would be useful for enabling this behavior. For now, use the pragma |
Thus, local is needed to keep $Anzahl consistent throughout matching. Adding ˹(?{ print "Anzahl am Ende ist $Anzahl.\n" })˼ at the end would print the correct count. To retain $Anzahl after matching, store it in a nonlocalized variable: every dynamic scope created during matching disappears afterward.
For example:
my $Anzahl = undef;
our $TmpAnzahl = 0;
$text =~ m{
^ (?> \d+ (?{ local($TmpAnzahl) = $TmpAnzahl + 1 }) \b | \w+ | \s+ )* $
(?{ $Anzahl = $TmpAnzahl }) # End-$Anzahl in einer Nicht-"local"-Variablen speichern.
}x;
if (defined $Anzahl) {
print "Anzahl ist $Anzahl.\n";
} else {
print "Kein Treffer\n";
}This is much work for a simple task, but the contrived example merely demonstrates the behavior of local variables inside regexes. A practical application appears under Emulating named subexpressions.
German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln
back to top