in reply to Closure Over Scalar?
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: <%-{-{-{-<
|
---|