XML technologies / Regular expressions / Perl / Unusual techniques with Perl regex extensions / Beware of my variables in code patterns

(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)

If you declare a my variable outside a regex and use it inside the regex, you must understand the subtleties of variable binding in Perl. Earlier, I recommended global variables in code patterns when in doubt. Set that advice aside for the following discussion, which is nevertheless not easy reading.

This contrived example illustrates the problem:

sub OptimiererTesten
{
  
    my $text  = shift; # Das erste Argument ist der Suchtext.
    my $start = undef; # Hier speichern wir, ab welcher Position die Suche beginnt.
  
    my $match = $text =~ m{
      (?{ $start = $-[0] if not defined $start}) # Erste Startposition abspeichern.
      \d # Die eigentliche Regex.
    }x;
    if (not defined $start) {
        print "Die ganze Mustersuche wurde wegoptimiert.\n";
        if ($match) {
            # Kann nicht passieren!
            print "Uh! Dennoch ein Treffer gefunden! Das kann nicht passieren!\n";
        }
    } elsif ($start == 0) {
        print "Der Match-Beginn wurde nicht optimiert.\n";
    } else {
        print "Der Optimierer hat die Regex bei Position $start angesetzt.\n"
    }
}

The program contains three my variables, but only $start matters here; the others are not used inside a code pattern. First, $start is set to the undefined value, then matching runs. The first regex component is a code pattern that records the starting position in $start, but only if that variable is still undefined. The attempt’s starting position comes from the first element of the array $-[0] (see Special variables controlled by matching).

Calling the function with

OptimiererTesten("test 123");

gives the expected result:

Der Optimierer hat die Regex bei Position 5 angesetzt.

Repeating exactly the same call gives, on the second occasion:

Die ganze Mustersuche wurde wegoptimiert.
 Uh! Dennoch ein Treffer gefunden! Das kann nicht passieren! 

Although the text and regex are identical, the result differs, and the second answer is wrong. Why? On the second run, $start inside the code pattern refers to a variable from the first run, when the regex was compiled. But $start elsewhere in the subroutine is a new variable, created at each call by the my statement at the start of the function.

The problem is caused by the binding of my variables. my variables in code patterns remain bound to the specific storage location created when the regex was compiled. (Regex compilation is covered in Regex compilation, the /o modifier, qr/.../, and efficiency.) Each call to OptimiererTesten creates a new variable $start, or a new instance of that variable. Yet $start inside the code pattern inexplicably still refers to the version existing at compilation time. The variable elsewhere in the function therefore does not receive the value seemingly stored inside the regex.

This type of variable binding is called a closure. The books Programmieren mit Perl or Object Oriented Perl describe closures and useful applications. Here, however, even Perl developers disagree on whether the closure is useful or merely confusing to many people.

My only recommendation is to avoid using my variables declared outside the regex in code patterns, unless the regex literal is recompiled at least as often as the external variable is recreated. In the example Emulating named subexpressions, the my variable $VerschachtelRegex is used in the subroutine RegexUmbauen. That is harmless there, because $VerschachtelRegex is created only once: there is just one instance. The my does not occur in a loop and therefore runs exactly once when the module starts. That instance remains throughout the program’s lifetime.

  

 

 

 

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