An approach that hasn't been mentioned so far is to encapsulate a
function and its data-to-be-closed-over in a module.
A my variable in a module is absolutely
private unless a getter/setter is explicitly defined for it.
All code in the
module is executed at the point in script compilation at which the
module is use-ed.
Initialization and checking of any complexity can be done.
(In some other languages, this is known as Compile Time Function
Evaluation - CTFE - and is a Big Deal.)
An extremely simple module with no exportation or OO can be used.
CloseOver.pm:
package CloseOver;
use strict;
use warnings;
my $FIXED_STRING = 'fixed_string'; # could be a constant
my %persistent = (42 => { $FIXED_STRING => 123 });
sub something {
my ($x,
) = @_;
$persistent{$x}{$FIXED_STRING} = rand;
}
END {
for my $k (keys %persistent) {
print "$k: $persistent{$k}{$FIXED_STRING}\n";
}
}
1;
Output:
Win8 Strawberry 5.8.9.5 (32) Thu 02/18/2021 21:14:15
C:\@Work\Perl\monks\QM
>perl
use strict;
use warnings;
use CloseOver;
CloseOver::something($_) for 1 .. 3;
^Z
42: 123
1: 0.69775390625
3: 0.8636474609375
2: 0.555877685546875
Update: Minor edit for clarity.
Give a man a fish: <%-{-{-{-<
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|