1constant::defer(3) User Contributed Perl Documentation constant::defer(3)
2
3
4
6 constant::defer -- constant subs with deferred value calculation
7
9 use constant::defer FOO => sub { return $some + $thing; },
10 BAR => sub { return $an * $other; };
11
12 use constant::defer MYOBJ => sub { require My::Class;
13 return My::Class->new_thing; }
14
16 "constant::defer" creates a subroutine which on the first call runs
17 given code to calculate its value, and on any subsequent calls just
18 returns that value, like a constant. The value code is discarded once
19 run, allowing it to be garbage collected.
20
21 Deferring a calculation is good if it might take a lot of work or
22 produce a big result but is only needed sometimes or only well into a
23 program run. If it's never needed then the value code never runs.
24
25 A deferred constant is generally not inlined or folded (see "Constant
26 Folding" in perlop) since it's not a single scalar value. In the
27 current implementation a deferred constant becomes a plain constant
28 after the first use, so may inline etc in code compiled after that (see
29 "IMPLEMENTATION" below).
30
31 See examples/simple.pl in the constant-defer source code for a complete
32 sample program.
33
34 Uses
35 Here are some typical uses.
36
37 • A big value or slow calculation only sometimes needed,
38
39 use constant::defer SLOWVALUE => sub {
40 long calculation ...;
41 return $result;
42 };
43
44 if ($option) {
45 print "s=", SLOWVALUE, "\n";
46 }
47
48 • A shared object instance created when needed then re-used,
49
50 use constant::defer FORMATTER =>
51 sub { return My::Formatter->new };
52
53 if ($something) {
54 FORMATTER()->format ...
55 }
56
57 • The value code might load requisite modules too, again deferring
58 that until actually needed,
59
60 use constant::defer big => sub {
61 require Some::Big::Module;
62 return Some::Big::Module->create_something(...);
63 };
64
65 • Once-only setup code can be created with no return value. The code
66 is garbage collected after the first run and becomes a do-nothing.
67 Remember to have an empty or "undef" return value so as not to keep
68 the last expression result alive forever.
69
70 use constant::defer MY_INIT => sub {
71 many lines of setup code ...;
72 return;
73 };
74
75 sub new {
76 MY_INIT();
77 ...
78 }
79
81 There are no functions as such, everything works through the "use"
82 import.
83
84 "use constant::defer NAME1=>SUB1, NAME2=>SUB2, ...;"
85 The parameters are name/subroutine pairs. For each one a sub
86 called "NAME" is created, running the given "SUB" the first time
87 its value is needed.
88
89 "NAME" defaults to the caller's package, or a fully qualified name
90 can be given. Remember that bareword stringizing of "=>" doesn't
91 act on a fully qualified name, so add quotes in that case.
92
93 use constant::defer 'Other::Package::BAR' => sub { ... };
94
95 For compatibility with the "constant" module a hash of name/sub
96 arguments is accepted too. But "constant::defer" doesn't need this
97 style since there's only ever one thing (a sub) following each
98 name.
99
100 use constant::defer { FOO => sub { ... },
101 BAR => sub { ... } };
102
103 # works without the hashref too
104 use constant::defer FOO => sub { ... },
105 BAR => sub { ... };
106
108 The value sub can return multiple values to make an array style
109 constant sub.
110
111 use constant::defer NUMS => sub { return ('one', 'two') };
112
113 foreach (NUMS) {
114 print $_,"\n";
115 }
116
117 The value sub is always run in array context, for consistency,
118 irrespective how the constant is used. The return from the new
119 constant sub is an array style
120
121 sub () { return @result }
122
123 If the value sub was a list-style return like "NUMS" shown above, then
124 this array-style return is slightly different. In scalar context a
125 list return means the last value (like a comma operator), but an array
126 return in scalar context means the number of elements. A multi-value
127 constant won't normally be used in scalar context, so the difference
128 shouldn't arise. The array style is easier for "constant::defer" to
129 implement and is the same as the plain "constant" module does.
130
132 If the constant is called with arguments then they're passed on to the
133 value sub. This can be good for constants used as object or class
134 methods. Passing anything to plain constants would be unusual.
135
136 A cute use for a class method style is to make a "singleton" instance
137 of the class. See examples/instance.pl in the constant-defer source
138 code for a complete program.
139
140 package My::Class;
141 use constant::defer INSTANCE => sub { my ($class) = @_;
142 return $class->new };
143 package main;
144 $obj = My::Class->INSTANCE;
145
146 Some care might be needed if letting a subclass object become the
147 parent "INSTANCE", though if a program only ever used the subclass then
148 that might in fact be desirable.
149
150 Subs created by "constant::defer" always have prototype "()", ensuring
151 they always parse the same way. The prototype has no effect when
152 called as a method like above, but if you want to make a plain call
153 with arguments then use "&" to bypass the prototype (see perlsub).
154
155 &MYCONST ('Some value');
156
158 Currently "constant::defer" creates a sub under the requested name and
159 when called it replaces that with a new constant sub the same as "use
160 constant" would make. This is compact and means that later loaded code
161 might be able to inline it.
162
163 It's fine to keep a reference to the initial sub and in fact that
164 happens quite normally if importing into another module (with the usual
165 "Exporter"), or an explicit "\&foo", or a "$package->can('foo')". The
166 initial sub changes itself to jump to the new constant, it doesn't re-
167 run the value code.
168
169 The jump is currently done by a "goto" to the new coderef, so it's a
170 touch slower than the new constant sub directly. A spot of XS would no
171 doubt make the difference negligible, perhaps to the point where
172 there'd be no need for a new sub, just have the initial transform
173 itself. If the new form looked enough like a plain constant it might
174 inline in later loaded code.
175
176 For reference, "Package::Constants" (as of its version 0.06) considers
177 "constant::defer" subrs as constants, both before and after the first
178 call which runs the value code. "Package::Constants" just looks for
179 prototype "sub foo () { }" functions, so any such subr rates as a
180 constant.
181
183 There's many ways to do "deferred" or "lazy" calculations.
184
185 • "Memoize" makes a function repeat its return. Results are cached
186 against the arguments, so it keeps the original code, whereas
187 "constant::defer" discards after the first run.
188
189 • "Class::Singleton" and its friends make a create-once
190 "My::Class->instance" method. "constant::defer" can go close with
191 the fakery shown under "ARGUMENTS" above, though without a
192 "has_instance()" to query.
193
194 • "Sub::Become" offers some syntactic sugar for redefining the
195 running subroutine, including to a constant.
196
197 • "Sub::SingletonBuilder" can create an instance function for a
198 class. It's designed for objects and so doesn't allow 0 or "undef"
199 as the return value.
200
201 • "Sub::StopCalls" mangles the code in its caller to put a value as a
202 constant there. The effect is to run a function just once at each
203 caller location, replacing it with the return value, though the
204 function can also choose to constant-ize only sometimes, based on
205 circumstances, arguments, etc.
206
207 • A $foo scalar variable can be rigged up to run code on its first
208 access. "Data::Lazy" uses a "tie". "Scalar::Defer" and
209 "Scalar::Lazy" use "overload" on an object. "Data::Thunk"
210 optimizes out the object from "Scalar::Defer" after the first run.
211 "Variable::Lazy" uses XS magic (removed after the first fetch) and
212 some parsing for syntactic sugar.
213
214 The advantage of a variable is that it interpolates in strings.
215 The disadvantages are it won't inline in later loaded code; bad XS
216 code might bypass the magic; and package variables aren't very
217 friendly when subclassing.
218
219 • "Object::Lazy" and "Object::Trampoline" rig up an object wrapper to
220 load and create an actual object only when a method is called,
221 dispatching to it and replacing the caller's $_[0]. The advantage
222 is you can pass the wrapper object around, etc, deferring creation
223 to an even later time than a sub or scalar can.
224
225 • "Object::Realize::Later", "Class::LazyObject" and
226 "Class::LazyFactory" help make a defer class which transforms lazy
227 stub objects to real ones when a method call is made. A separate
228 defer class is required for each real class.
229
230 • "once.pm" sets up a run-once code block, but with no particular
231 return value and not discarding the code after run.
232
233 • "Class::LazyLoad" and "deferred.pm" load code on a class method
234 call such as object creation. They're mainly to defer module
235 loading rather than calculation of a particular value.
236
237 • "Tie::LazyList" and "Tie::Array::Lazy" makes array elements
238 calculated on-demand from a generator function. "Hash::Lazy" does
239 a similar thing for hashes. "Tie::LazyFunction" hides a function
240 behind a scalar; its laziness is in the arguments which are not
241 evaluated until used.
242
244 constant, perlsub, constant::lexical
245
246 Memoize, Attribute::Memoize, Memoize::Attrs, Class::Singleton,
247 Data::Lazy, Scalar::Defer, Scalar::Lazy, Data::Thunk, Variable::Lazy,
248 Sub::Become, Sub::SingletonBuilder, Sub::StopCalls, Object::Lazy,
249 Object::Trampoline, Object::Realize::Later, once, Class::LazyLoad,
250 deferred
251
253 http://user42.tuxfamily.org/constant-defer/index.html
254
256 Copyright 2009, 2010, 2011, 2012, 2015 Kevin Ryde
257
258 constant-defer is free software; you can redistribute it and/or modify
259 it under the terms of the GNU General Public License as published by
260 the Free Software Foundation; either version 3, or (at your option) any
261 later version.
262
263 constant-defer is distributed in the hope that it will be useful, but
264 WITHOUT ANY WARRANTY; without even the implied warranty of
265 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
266 General Public License for more details.
267
268 You should have received a copy of the GNU General Public License along
269 with constant-defer. If not, see <http://www.gnu.org/licenses/>.
270
271
272
273perl v5.32.1 2021-01-27 constant::defer(3)