Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Closure Over Scalar?

by AnomalousMonk (Archbishop)
on Feb 19, 2021 at 02:48 UTC ( [id://11128550]=note: print w/replies, xml ) Need Help??


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:  <%-{-{-{-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11128550]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2024-06-25 09:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.