Sub::Clone - Clone subroutine refs for garbage collection/blessing purposes
use Sub::Clone;
A surprising fact about Perl is that anonymous subroutines that do not close over variables are actually shared, and do not garbage collect until global destruction:
sub get_callback { return sub { "hi!" }; } my $first = get_callback(); my $second = get_callback(); warn "$first == $second"; # prints the same refaddr
This means that blessing such a sub would change all other copies (since they are, in fact, not copies at all), and that DESTROY will never be called.
DESTROY
Sub::Clone uses Sub::Exporter so its import has all the implied goodness (renaming, etc).
import
Returns true if CVf_CLONED is true (meaning that this subroutine is a clone of a proto sub and being refcounted).
CVf_CLONED
Returns a clone of the sub, that is guaranteed to be refcounted, and can be safely blessed.
Clones the sub if it's not is_cloned.
is_cloned
This module is implemented in both XS and pure Perl, and the reference counting behavior of the two is slightly different.
The XS implementation of clone_sub uses cv_clone internally, the function that captures closure state into a clone of the code ref struct (sharing the optree etc), which means that it's a real clone (the prototype's reference count does not go up), whereas the pure Perl version must wrap the proto.
clone_sub
cv_clone
This means that in the pure Perl version DESTROY might not be called as early for the cloned sub as the XS version.
This module is maintained using Darcs. You can get the latest version from http://nothingmuch.woobling.org/code, and use darcs send to commit changes.
darcs send
Yuval Kogman <nothingmuch@woobling.org>
Copyright (c) 2008 Yuval Kogman. All rights reserved This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
To install Sub::Clone, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Sub::Clone
CPAN shell
perl -MCPAN -e shell install Sub::Clone
For more information on module installation, please visit the detailed CPAN module installation guide.