Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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.

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;


Win8 Strawberry (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

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

  • 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.
Log In?

What's my password?
Create A New User
Domain Nodelet?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2024-06-18 06:27 GMT
Find Nodes?
    Voting Booth?

    No recent polls found

    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.