The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Sub::Clone - Clone subroutine refs for garbage collection/blessing purposes

SYNOPSIS

        use Sub::Clone;

DESCRIPTION

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.

EXPORTS

Sub::Clone uses Sub::Exporter so its import has all the implied goodness (renaming, etc).

is_cloned $sub

Returns true if CVf_CLONED is true (meaning that this subroutine is a clone of a proto sub and being refcounted).

clone_sub $sub

Returns a clone of the sub, that is guaranteed to be refcounted, and can be safely blessed.

clone_if_immortal $sub

Clones the sub if it's not is_cloned.

PURE PERL VS XS

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.

This means that in the pure Perl version DESTROY might not be called as early for the cloned sub as the XS version.

VERSION CONTROL

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.

AUTHOR

Yuval Kogman <nothingmuch@woobling.org>

COPYRIGHT

        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.