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
once expression is evaluated, EXPR is evaluated, and (if everything proceeds normally)
once stores the value it yielded and also yields the same value. When the same
once expression 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
once operator in the source.
Because EXPR is not evaluated until the
once operator is being evaluated, it can refer to and use any aspects of the lexical and dynamic environment as they exist at runtime of the
once operator. 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
once expression 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
once operator 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.