7 our $VERSION = '1.003000';
8 $VERSION = eval $VERSION;
10 our @EXPORT = qw(defer_sub undefer_sub);
16 my ($target, $maker, $undeferred_ref) = @{
17 $DEFERRED{$deferred}||return $deferred
19 return ${$undeferred_ref}
20 if ${$undeferred_ref};
21 ${$undeferred_ref} = my $made = $maker->();
23 # make sure the method slot has not changed since deferral time
24 if (defined($target) && $deferred eq *{_getglob($target)}{CODE}||'') {
25 no warnings 'redefine';
27 # I believe $maker already evals with the right package/name, so that
28 # _install_coderef calls are not necessary --ribasushi
29 *{_getglob($target)} = $made;
31 $DEFERRED{$made} = $DEFERRED{$deferred};
38 $DEFERRED{$deferred||''};
42 my ($target, $maker) = @_;
46 $undeferred ||= undefer_sub($deferred);
49 $DEFERRED{$deferred} = [ $target, $maker, \$undeferred, $deferred ];
50 _install_coderef($target => $deferred) if defined $target;
55 %DEFERRED = map { $_->[3] => $_ } values %DEFERRED;
62 Sub::Defer - defer generation of subroutines until they are first called
68 my $deferred = defer_sub 'Logger::time_since_first_log' => sub {
73 Logger->time_since_first_log; # returns 0 and replaces itself
74 Logger->time_since_first_log; # returns time - $t
78 These subroutines provide the user with a convenient way to defer creation of
79 subroutines and methods until they are first called.
85 my $coderef = defer_sub $name => sub { ... };
87 This subroutine returns a coderef that encapsulates the provided sub - when
88 it is first called, the provided sub is called and is -itself- expected to
89 return a subroutine which will be goto'ed to on subsequent calls.
91 If a name is provided, this also installs the sub as that name - and when
92 the subroutine is undeferred will re-install the final version for speed.
96 my $coderef = undefer_sub \&Foo::name;
98 If the passed coderef has been L<deferred|/defer_sub> this will "undefer" it.
99 If the passed coderef has not been deferred, this will just return it.
101 If this is confusing, take a look at the example in the L</SYNOPSIS>.
105 See L<Moo> for support and contact information.
109 See L<Moo> for authors.
111 =head1 COPYRIGHT AND LICENSE
113 See L<Moo> for the copyright and license.