XML technologies / Regular expressions / Perl / Perl-specific regex topics / Dynamic scope: effects on pattern matching
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
The two kinds of variables in Perl, global and private, and the concept of dynamic scope are interesting in themselves. For our purposes, they matter particularly for variables accessible after matching. The following sections explain this concept, especially in connection with regexes.
Global and private variables
Put simply, Perl has two variable types: global and private. Private variables are declared with my(...). Global variables need no declaration; they are created automatically on first use. Globals are accessible throughout the program, whereas private variables are visible only in their lexically enclosing block. A private variable can be accessed only between its my declaration and the end of the block containing that my .
Using global variables is considered poor programming style, except for the many special globals such as $1, $_ and @ARGV. Ordinary user-created variables are global unless declared with my. Globals can be placed in namespaces called packages , but remain global variables. A global variable $Debug in the package Acme::Widget has the fully qualified name $Acme::Widget::Debug, but however you refer to it, it remains global. With use strict;, all globals except special variables must use their fully qualified names or be declared with our . (our declares a name, not a new variable; see the Perl documentation.)
Dynamically scoped values
Dynamic scoping is an interesting concept found in few languages. Its connection with regexes will soon become clear. In brief, Perl saves the value of a global variable you want to modify. You may then do whatever you like with the variable. When the block is exited, the global automatically regains its old value. Saving the original value is called creating a new dynamic scope or localization.
There are several reasons to do this, for example temporarily changing program state stored in a global variable. Suppose the package Acme::Widget has a variable called $Acme::Widget::Debug that enables debugging information when nonzero. We can temporarily enable that debugging:
{
local($Acme::Widget::Debug) = 1; # Debugging einschalten.
# Acme::Widget mit Debugging verwenden.
.
.
.
}
# $Acme::Widget::Debug hat wieder den alten Wert.The misleadingly named function local creates a new dynamic scope. Let me be quite explicit: local does not create a new variable. local performs an action; it is not a variable declaration.
Calling local with a global variable does the following:
The variable’s old value is saved.
The variable receives a new value, either the value assigned to the
localoperator or otherwiseundef.When the block containing the
localdirective is exited, the saved value becomes available again in the original global variable.
Thus, “local” refers more to time. The localized value exists only while the enclosing block’s code is active. Even a subroutine called from that block sees only the new localized value, since the variable remains global. The sole difference from an unlocalized global is that leaving the block automatically restores its old value.
Automatic saving and restoration are about all local really does. Despite all the confusion surrounding local , it is no more complicated than the following table shows.
Table: the meaning of local.
Ordinary Perl | Equivalent meaning | ||
|---|---|---|---|
|
| ||
|
| ||
| |||
|
| ||
|
| ||
| |||
|
|
| |
Conveniently, you can assign a value directly to local($Var). This is exactly equivalent to a separate assignment immediately after local. Omitting the parentheses forces scalar context.
A practical example: a carelessly written library function produces numerous warnings such as ›Use of uninitialized value...‹. Like every good Perl programmer, you use the -w option, but the library’s author apparently did not. This is annoying, but you cannot change the function. What can you do without abandoning -w? For the duration of that lousy function call, set the variable $^W to zero with local . The variable $^W corresponds to the -w command-line option. Its identifier ^W can be written as two characters, caret and W, or as an actual Control-W.
{
local $^W = 0; # Warnungen ausschalten
UebleFunktion(...);
}
# nach dem Verlassen des Blocks hat $^W wieder den alten WertCalling local makes an internal copy of the value of $^W. That same $^W receives the new value zero in the local statement. When UebleFunktion is called, and also within that function, Perl sees only this value and issues no warnings. After the call, $^W still has the value zero.
So far, this is no different from not using local and simply setting $^W to zero. But upon leaving the block, $^W automatically regains its value from before the local statement. The change was local in time, lasting only as long as the block. An explicit temporary variable could achieve the same effect, as in the table above, but local makes it easier.
For completeness, let us examine using my instead of local . (This is an academic exercise: Perl does not allow my with this special variable.) With my , a new variable is created, initially undefined. It is visible only within the lexical block where declared, more precisely between the my declaration and the end of the block containing the my . It has no connection to any other variable, not even a global with the same name. It is invisible outside the block, even to a function called from that block such as UebleFunktion. In our example, a variable $^W would be created and assigned zero, but never used afterward. Inside UebleFunktion, Perl uses the global variable $^W, unrelated to the newly created my variable. Warnings therefore still appear.
An analogy: transparencies
A useful analogy for local is an overhead-projector transparency on which you can scribble over the text beneath, literally overwriting a variable. You and anyone looking, including subroutines and interrupt handlers, see only the new text. The original remains covered until the block is exited; then the transparency is automatically removed, with every change made since local, when the transparency was laid down.
This analogy is also more accurate than saying “the original value is saved”. local does not really copy the value; it inserts a new value at the front of a list consulted whenever the variable is used. The old value is hidden. Leaving a block removes every value added since that block began. Values can be added to the list with local , but now we reach the reason for examining localization in such detail: Regex side-effect variables are automatically dynamically scoped.
Regex side effects and dynamic scope
What does dynamic scope have to do with regexes? A lot. Every successful match sets variables such as $& , the text of the entire match, and $1, the first group’s text; the next section examines these more closely. When first set in a block by a successful regex , they are automatically given a new dynamic scope.
To see the benefit, note that every subroutine forms a new block. A regex used within it automatically gives the resulting side-effect variables a new dynamic scope. Since their values are restored when the block is exited, that is, when the function returns, a subroutine cannot change the caller’s values.
An example:
if (m/(...)/) {
MachIrgendwasAnderes();
print "Gefundener Text: $1.\n";
}Because $1 receives a new dynamic scope in every block where it is set, this code need not worry whether the routine MachIrgendwasAnderes contains a regex that might change $1. Any change to $1 within the subroutine is restricted to its block or a nested block. Thus, the function call cannot affect the $1 in the print statement.
Automatic dynamic scoping can help even where no problem is initially apparent:
if ($resultat =~ m/ERROR=(.*)/) {
warn "He, melde $Config{perladmin} den Fehler: $1!\n";
}The standard-library module Config defines the associative array %Config; its element $Config{perladmin} contains the local Perl administrator’s email address. This example would be very confusing without automatic dynamic scoping for $1 . %Config is not a simple hash, but a package-bound variable, a tied variable, whose use triggers a subroutine call behind the scenes. That function really does use regexes, executed between the regex in the if statement and the use of $1. Without its own dynamic scope in the function, the variable would overwrite “our” $1. As things stand, changes by $Config{...} routines are prevented.
Dynamic and lexical scope
Used properly, dynamic scoping has many advantages, but careless use of local can make programs very obscure. When reading a program, the local statement is often far removed from a variable’s use in a block inside a subroutine.
As noted, my(...) creates a new private variable with lexical scope. This is roughly the opposite of a global variable, but has almost nothing to do with dynamic scoping, except that variables created with my cannot be localized. local performs an action, whereas my combines an action and a declaration.
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