I’m looking for advice on Perl best practices. I wrote a script which had a complicated regular expression:
my $regex = qr/complicated/;
# ...
sub foo {
# ...
if (/$regex/)
# ...
}
where foo is a function which is called often, and $regex 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?
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.
At the moment I have something like
my ($regex, $DT);
sub driver {
$regex = qr/complicated/;
$DT = dateTime();
# ...
}
# ...
driver();
which at least slightly segregates it. But perhaps there are better ways.
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.
If you’re using perl 5.10+, use a
statevariable.will only call
something_expensiveonce.If you need to work with older perls, then use a lexical variable in an outer scope with an extra pair of braces:
this keeps
$foofrom leaking to anyone except forwomble.