NAME

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

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

constant::defer creates a subroutine which runs given code to calculate its value on the first call, and from then on returns just 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 and/or produce a big result, yet is only needed sometimes or only well into a program run. If it's never needed then the code never runs.

Here are some typical uses.

  • A big value or slow calculation put off,

    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 statement'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 is accomplished through the use import.

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

The parameters are name/subroutine pairs. For each a sub called NAME is created, running the 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 this is not needed with constant::defer since there's only ever one thing (a sub) following the name.

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. For zero or one return values this makes no difference. But for two or more any list return in the value sub becomes an array return from the constant like

sub () { return @result }

List versus array return are subtly different in scalar context; a list gives the last value like a comma operator, an array gives the number of elements. The array style is easier to implement for constant::defer and is the same as the plain constant module does.

ARGUMENTS

If the constant sub 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, but anything else to plain constants would be unusual.

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

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

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 to pass arguments in a plain call then use & to bypass the prototype (see perlsub).

&MYCONST ('Some value');

IMPLEMENTATION

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

It's fine to keep a reference to the initial sub and in fact that happens quite normally if imported into another modules (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 of a scalar, so it's a touch slower than the new constant sub directly. A spot of XS would no doubt make the difference negligible, and in fact probably to the point where there'd be no need for a new sub, just have the initial transform itself.

OTHER WAYS

There's more than one way to do "deferred" or "lazy" calculations. In fact there's a lot of ways.

  • Memoize makes a function repeat its return. It caches results against different arguments, so it preserves the original code whereas constant::defer discards after the first run.

  • Class::Singleton and friends make a create-once My::Class->instance method. constant::defer can get close with the fakery under "ARGUMENTS" above, though without a has_instance to query.

  • A scalar can be rigged up to run code on its first access. The advantage of a variable is that it interpolates in strings, but it won't inline in later loaded code, sloppy XS code might bypass the magic, and public package variables aren't terribly friendly when subclassing.

    Modules for this include: Data::Lazy using a tie. Scalar::Defer and Scalar::Lazy using overload on an object. And Data::Thunk optimizing out the object from Scalar::Defer after the first run.

  • Object::Lazy and Object::Realize::Later rig up an object to only load its class and create itself when a method is called. The advantage is you can access the value, pass it around, etc, deferring to an even later point than a sub or scalar.

SEE ALSO

constant, perlsub

Memoize, Attribute::Memoize, Memoize::Attrs, Class::Singleton, Data::Lazy, Scalar::Defer, Scalar::Lazy, Data::Thunk, Object::Lazy Object::Realize::Later

HOME PAGE

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

COPYRIGHT

Copyright 2009 Kevin Ryde

constant-defer is free software; you can redistribute it and/or modify it under the terms of the GNU 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 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

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