Memoize::Once - memoise expression on first execution
use Memoize::Once qw(once); $value = once(expensive_computation());
This module supplies an operator that causes an expression to be evaluated only once per program run, memoising its value for the remainder of the run.
Evaluate EXPR once and memoise its value. The first time a
onceexpression is evaluated, EXPR is evaluated, and (if everything proceeds normally)
oncestores the value it yielded and also yields the same value. When the same
onceexpression is evaluated subsequently, it yields the value that EXPR yielded the first time, without evaluating EXPR again. There is one instance of this memoisation for each instance of the
onceoperator in the source.
Because EXPR is not evaluated until the
onceoperator is being evaluated, it can refer to and use any aspects of the lexical and dynamic environment as they exist at runtime of the
onceoperator. However, if EXPR yields different results depending on variable aspects of the environment, such as arguments of the surrounding subroutine, then the memoisation is probably inappropriate. That is, EXPR can't sensibly depend on the specific features of an invocation of the surrounding code, but can depend on the general features that are consistent to all invocations.
If evaluation of EXPR results in an exception, rather than yielding a normal value, no value will be memoised. A value will be memoised the first time that EXPR does yield a normal value. If multiple evaluations of EXPR are in progress simultaneously (due to recursion), and multiple instances of it yield a normal value, then the first yielded value will be memoised and others will be ignored. A
onceexpression will never yield a value other than the one it memoised.
EXPR is always evaluated in scalar context, regardless of the context in which the
onceoperator appears. To memoise a list, write
B::Deparse will generate incorrect source when deparsing
once expressions. The code that it displays gives a rough indication of how memoisation operates, but appears buggy in detail. In fact the
once operator works through some custom ops that cannot be adequately represented in pure Perl.
Andrew Main (Zefram) <email@example.com>
Copyright (C) 2011 Andrew Main (Zefram) <firstname.lastname@example.org>
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.