Kevin Ryde > constant-defer-5 > constant::defer



Annotate this POD



Open  0
View/Report Bugs
Module Version: 5   Source  


constant::defer -- constant subs with deferred value calculation


 use constant::defer FOO => sub { return $some + $thing; },
                     BAR => sub { return $an * $other; };

 use constant::defer MYOBJ => sub { require My::Class;
                                    return My::Class->new_thing; }


constant::defer creates a subroutine which on the first call runs given code to calculate its value, and on the second and subsequent calls just returns that value, like a constant. The value code is discarded once run, allowing it to be garbage collected.

Deferring a calculation is good if it might take a lot of work or produce a big result, but is only needed sometimes or only well into a program run. If it's never needed then the value code never runs.

A deferred constant is generally not inlined or folded (see "Constant Folding" in perlop) like a plain constant since it's not a single scalar value. In the current implementation a deferred constant becomes a plain one after the first use, so may inline etc in code compiled after that (see "IMPLEMENTATION" below).


Here are some typical uses.


There are no functions as such, everything works through the use import.

use constant::defer NAME1=>SUB1, NAME2=>SUB2, ...;

The parameters are name/subroutine pairs. For each one a sub called NAME is created, running the given SUB the first time its value is needed.

NAME defaults to the caller's package, or a fully qualified name can be given. Remember that the bareword stringizing of => doesn't act on a qualified name, so add quotes in that case.

    use constant::defer 'Other::Package::BAR' => sub { ... };

For compatibility with the constant module a hash of name/sub arguments is accepted too. But constant::defer doesn't need that since there's only ever one thing (a sub) following each name.

    use constant::defer { FOO => sub { ... },
                          BAR => sub { ... } };

    # works without the hashref too
    use constant::defer FOO => sub { ... },
                        BAR => sub { ... };


The value sub can return multiple values to make an array style constant sub.

    use constant::defer NUMS => sub { return ('one', 'two') };

    foreach (NUMS) {
       print $_,"\n";

The value sub is always run in array context, for consistency, irrespective how the constant is used. The return from the new constant sub is an array style

    sub () { return @result }

If the value sub was a list-style return like NUMS shown above, then this array-style return is slightly different. In scalar context a list return means the last value (like a comma operator), but an array return in scalar context means the number of elements. A multi-value constant won't normally be used in scalar context, so the difference shouldn't arise. The array style is easier for constant::defer to implement and is the same as the plain constant module does.


If the constant is called with arguments then they're passed on to the value sub. This can be good for constants used as object or class methods. Passing anything to plain constants would be unusual.

One cute use for a class method style is to make a "singleton" instance of the class. See examples/ in the sources for a complete program.

    package My::Class;
    use constant::defer INSTANCE => sub { my ($class) = @_;
                                          return $class->new };
    package main;
    $obj = My::Class->INSTANCE;

A subclass might want to be careful about letting a subclass object get into the parent INSTANCE, though if a program only ever used the subclass then that might in fact be desirable.

Subs created by constant::defer always have prototype (), ensuring they always parse the same way. The prototype has no effect when called as a method like above, but if you want a plain call with arguments then use & to bypass the prototype (see perlsub).

    &MYCONST ('Some value');


Currently constant::defer creates a sub under the requested name and when called it replaces that with a new constant sub the same as use constant would make. This is compact and means that later loaded code might be able to inline it.

It's fine to keep a reference to the initial sub and in fact that happens quite normally if importing into another module (with the usual Exporter), or an explicit \&foo, or a $package->can('foo'). The initial sub changes itself to jump to the new constant, it doesn't re-run the value code.

The jump is currently done by a goto to the new coderef, so it's a touch slower than the new constant sub directly. A spot of XS would no doubt make the difference negligible, in fact perhaps to the point where there'd be no need for a new sub, just have the initial transform itself. If the new form looked enough like a plain constant it might inline in later loaded code.

For reference, Package::Constants (as of version 0.02) considers constant::defer subrs as constants, both before and after the first call that runs the value code. Package::Constants just looks for prototyped sub foo () { } functions, so any such subr rates as a constant.


There's many ways to do "deferred" or "lazy" calculations.


constant, perlsub, constant::lexical

Memoize, Attribute::Memoize, Memoize::Attrs, Class::Singleton, Data::Lazy, Scalar::Defer, Scalar::Lazy, Data::Thunk, Variable::Lazy, Sub::Become, Sub::SingletonBuilder, Object::Lazy, Object::Trampoline, Object::Realize::Later, once, Class::LazyLoad, deferred



Copyright 2009, 2010, 2011 Kevin Ryde



You should have received a copy of the GNU General Public License along with constant-defer. If not, see <>.

syntax highlighting: