6 use Scalar::Util qw(weaken);
8 our $VERSION = '1.003001';
9 $VERSION = eval $VERSION;
11 our @EXPORT = qw(defer_sub undefer_sub);
17 my ($target, $maker, $undeferred_ref) = @{
18 $DEFERRED{$deferred}||return $deferred
20 return ${$undeferred_ref}
21 if ${$undeferred_ref};
22 ${$undeferred_ref} = my $made = $maker->();
24 # make sure the method slot has not changed since deferral time
25 if (defined($target) && $deferred eq *{_getglob($target)}{CODE}||'') {
26 no warnings 'redefine';
28 # I believe $maker already evals with the right package/name, so that
29 # _install_coderef calls are not necessary --ribasushi
30 *{_getglob($target)} = $made;
32 weaken($DEFERRED{$made} = $DEFERRED{$deferred});
39 $DEFERRED{$deferred||''};
43 my ($target, $maker) = @_;
47 $undeferred ||= undefer_sub($deferred_info->[3]);
50 $deferred_info = [ $target, $maker, \$undeferred, $deferred ];
51 weaken($DEFERRED{$deferred} = $deferred_info);
52 _install_coderef($target => $deferred) if defined $target;
57 %DEFERRED = map { defined $_ ? ($_->[3] => $_) : () } values %DEFERRED;
58 weaken($_) for values %DEFERRED;
65 Sub::Defer - defer generation of subroutines until they are first called
71 my $deferred = defer_sub 'Logger::time_since_first_log' => sub {
76 Logger->time_since_first_log; # returns 0 and replaces itself
77 Logger->time_since_first_log; # returns time - $t
81 These subroutines provide the user with a convenient way to defer creation of
82 subroutines and methods until they are first called.
88 my $coderef = defer_sub $name => sub { ... };
90 This subroutine returns a coderef that encapsulates the provided sub - when
91 it is first called, the provided sub is called and is -itself- expected to
92 return a subroutine which will be goto'ed to on subsequent calls.
94 If a name is provided, this also installs the sub as that name - and when
95 the subroutine is undeferred will re-install the final version for speed.
99 my $coderef = undefer_sub \&Foo::name;
101 If the passed coderef has been L<deferred|/defer_sub> this will "undefer" it.
102 If the passed coderef has not been deferred, this will just return it.
104 If this is confusing, take a look at the example in the L</SYNOPSIS>.
108 See L<Moo> for support and contact information.
112 See L<Moo> for authors.
114 =head1 COPYRIGHT AND LICENSE
116 See L<Moo> for the copyright and license.