Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: References for ano subs fixed at compile time?

by dave_the_m (Prior)
on Jun 18, 2013 at 22:51 UTC ( #1039686=note: print w/replies, xml ) Need Help??

in reply to References for ano subs fixed at compile time?

Here's how it it works. Consider the following code:
$f = sub { .... };
At compile time, the code within {} is compiled into a prototype anonymous sub (CV), which is squirrelled away somewhere. At run time, the action of sub {...} is to make a copy of that sub (allocating a new CV), and then return a reference to that new CV.

As an optimisation, if the sub isn't a closure, then rather than copying the CV, a reference is just returned to the original prototype CV. This optimisation isn't perfect; in particular if one blesses $f, then the prototype CV gets blessed, and any new executions of that $f = sub {...} assignment get a blessed coderef.

Finally, note that perl maintains a pool of spare CVs; when one is freed, it gets returned to the pool and that may get reused soon.

Of course, these are implementation details which are subject to change.


Replies are listed 'Best First'.
Re^2: References for ano subs fixed at compile time?
by ikegami (Pope) on Jun 20, 2013 at 07:30 UTC
    sub f(&) { my ($cr) = @_; push @keep_alive, $cr; say $cr; } my $x = '...'; f { '...' } for 1..2; f { $x } for 1..2;
    CODE(0x3396f4) \ same for non-capturing CODE(0x3396f4) / CODE(0x24b1cc) \ different for capturing CODE(0x338c04) /

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1039686]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2018-06-22 04:36 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (121 votes). Check out past polls.