title: Static local variables in Perl
body: <p>I'm looking for advice on Perl best practices. I wrote a script which had a complicated regular expression:</p>
  
  <pre><code>my $regex = qr/complicated/;
  
  # ...
  
  sub foo {
    # ...
  
    if (/$regex/)
    # ...
  }
  </code></pre>
  
  <p>where <code>foo</code> is a function which is called often, and <code>$regex</code> is not used outside that function.  What is the best way to handle situations like this?  I only want it to be interpreted once, since it's long and complicated.  But it seems a bit questionable to have it in global scope since it's only used in that sub. Is there a reasonable way to declare it static?</p>
  
  <p>A similar issue arises with another possibly-unjustified global. It reads in the current date and time and formats it appropriately. This is also used many times, and again only in one function. But in this case it's even more important that it not be re-initialized, since I want all instances of the date-time to be the same from a given invocation of the script, even if the minutes roll over during execution.</p>
  
  <p>At the moment I have something like</p>
  
  <pre><code>my ($regex, $DT);
  
  sub driver {
    $regex = qr/complicated/;
    $DT = dateTime();
    # ...
  }
  
  # ...
  
  driver();
  </code></pre>
  
  <p>which at least slightly segregates it. But perhaps there are better ways.</p>
  
  <p>Again: I'm looking for the right way to do this, in terms of following best practices and Perl idioms. Performance is nice but readability and other needs take priority if I can't have everything.</p>