Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

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.


Comment on Re: References for ano subs fixed at compile time?
Download Code
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 the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2016-06-01 04:12 GMT
Find Nodes?
    Voting Booth?

    No recent polls found