SYNOPSIS

 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; }

DESCRIPTION

\*(C`constant::defer\*(C' 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 \*(L"Constant Folding\*(R" in perlop) like a plain \*(C`constant\*(C' 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 \*(L"\s-1IMPLEMENTATION\s0\*(R" below).

Uses

Here are some typical uses.

  • A big value or slow calculation only sometimes needed, use constant::defer SLOWVALUE => sub { long calculation ...; return $result; };

    if ($option) { print "s=", SLOWVALUE, "\n"; }

  • A shared object instance created when needed then re-used, use constant::defer FORMATTER => sub { return My::Formatter->new };

    if ($something) { FORMATTER()->format ... }

  • The value code might load requisite modules too, again deferring that until actually needed, use constant::defer big => sub { require Some::Big::Module; return Some::Big::Module->create_something(...); };

  • Once-only setup code can be created with no return value. The code is garbage collected after the first run and becomes a do-nothing. Remember to have an empty return statement so as not to keep the last expression's value alive forever. use constant::defer MY_INIT => sub { many lines of setup code ...; return; };

    sub new { MY_INIT(); ... }

IMPORTS

There are no functions as such, everything works through the \*(C`use\*(C' import. The parameters are name/subroutine pairs. For each one a sub called \*(C`NAME\*(C' is created, running the given \*(C`SUB\*(C' the first time its value is needed. \*(C`NAME\*(C' defaults to the caller's package, or a fully qualified name can be given. Remember that the bareword stringizing of \*(C`=>\*(C' doesn't act on a qualified name, so add quotes in that case. use constant::defer 'Other::Package::BAR' => sub { ... }; For compatibility with the \*(C`constant\*(C' module a hash of name/sub arguments is accepted too. But \*(C`constant::defer\*(C' 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 { ... };

MULTIPLE VALUES

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 \*(C`NUMS\*(C' 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 \*(C`constant::defer\*(C' to implement and is the same as the plain \*(C`constant\*(C' module does.

ARGUMENTS

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 \*(L"singleton\*(R" instance of the class. See examples/instance.pl 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 \*(C`INSTANCE\*(C', though if a program only ever used the subclass then that might in fact be desirable.

Subs created by \*(C`constant::defer\*(C' always have prototype \*(C`()\*(C', 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 \*(C`&\*(C' to bypass the prototype (see perlsub).

&MYCONST ('Some value');

IMPLEMENTATION

Currently \*(C`constant::defer\*(C' creates a sub under the requested name and when called it replaces that with a new constant sub the same as \*(C`use constant\*(C' 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 \*(C`Exporter\*(C'), or an explicit \*(C`\&foo\*(C', or a \*(C`$package->can('foo')\*(C'. 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 \*(C`goto\*(C' to the new coderef, so it's a touch slower than the new constant sub directly. A spot of \s-1XS\s0 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, \*(C`Package::Constants\*(C' (as of version 0.02) considers \*(C`constant::defer\*(C' subrs as constants, both before and after the first call that runs the value code. \*(C`Package::Constants\*(C' just looks for prototyped \*(C`sub foo () { }\*(C' functions, so any such subr rates as a constant.

OTHER WAYS TO DO IT

There's many ways to do \*(L"deferred\*(R" or \*(L"lazy\*(R" calculations.

  • \*(C`Memoize\*(C' makes a function repeat its return. Results are cached against the arguments, so it keeps the original code whereas \*(C`constant::defer\*(C' discards after the first run.

  • \*(C`Class::Singleton\*(C' and friends make a create-once \*(C`My::Class->instance\*(C' method. \*(C`constant::defer\*(C' can get close with the fakery shown under \*(L"\s-1ARGUMENTS\s0\*(R" above, though without a \*(C`has_instance\*(C' to query.

  • \*(C`Sub::Become\*(C' offers some syntactic sugar for redefining the running subroutine, including to a constant.

  • \*(C`Sub::SingletonBuilder\*(C' can create an instance function for a class. It's geared towards objects and so won't allow 0 or \*(C`undef\*(C' as the return value.

  • A scalar can be rigged up to run code on its first access. \*(C`Data::Lazy\*(C' uses a \*(C`tie\*(C'. \*(C`Scalar::Defer\*(C' and \*(C`Scalar::Lazy\*(C' use \*(C`overload\*(C' on an object. \*(C`Data::Thunk\*(C' optimizes out the object from \*(C`Scalar::Defer\*(C' after the first run. \*(C`Variable::Lazy\*(C' uses \s-1XS\s0 magic removed after the first fetch and some parsing for syntactic sugar. The advantage of a variable is that it interpolates in strings, but it won't inline in later loaded code; sloppy \s-1XS\s0 code might bypass the magic; and package variables aren't very friendly when subclassing.

  • \*(C`Object::Lazy\*(C' and \*(C`Object::Trampoline\*(C' rig up an object wrapper to load and create an actual object only when a method is called, dispatching to it and replacing the callers $_[0]. The advantage is you can pass the wrapper object around, etc, deferring creation to an even later point than a sub or scalar can.

  • \*(C`Object::Realize::Later\*(C', \*(C`Class::LazyObject\*(C' and \*(C`Class::LazyFactory\*(C' help make a defer class which transforms lazy stub objects to real ones when a method call is made. A separate defer class is required for each real class.

  • \*(C`once.pm\*(C' sets up a run-once code block, but with no particular return value and not discarding the code after run.

  • \*(C`Class::LazyLoad\*(C' and \*(C`deferred\*(C' load code on a class method call such as object creation. They're more about module loading than a defer of a particular value.

  • \*(C`Tie::LazyList\*(C' and \*(C`Tie::Array::Lazy\*(C' makes an array calculate values on-demand from a generator function. \*(C`Hash::Lazy\*(C' does a similar thing for hashes. \*(C`Tie::LazyFunction\*(C' hides a function behind a scalar; its laziness is in the argument evaluation, the function is called every time.

RELATED TO constant::defer…

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

HOME PAGE

http://user42.tuxfamily.org/constant-defer/index.html

COPYRIGHT

Copyright 2009, 2010, 2011 Kevin Ryde

constant-defer is free software; you can redistribute it and/or modify it under the terms of the \s-1GNU\s0 General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version.

constant-defer is distributed in the hope that it will be useful, but \s-1WITHOUT\s0 \s-1ANY\s0 \s-1WARRANTY\s0; without even the implied warranty of \s-1MERCHANTABILITY\s0 or \s-1FITNESS\s0 \s-1FOR\s0 A \s-1PARTICULAR\s0 \s-1PURPOSE\s0. See the \s-1GNU\s0 General Public License for more details.

You should have received a copy of the \s-1GNU\s0 General Public License along with constant-defer. If not, see <http://www.gnu.org/licenses/>.