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


In reply to Re: Closure Over Scalar? by AnomalousMonk
in thread Closure Over Scalar? by QM

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.