constant::defer(3pm)

πŸ“¦
version 6 Β· 7 versions
, in ubuntu noble, ubuntu resolute, ubuntu stonking

πŸ’– constant::defer(3pm) πŸ’–

okay bestie, welcome to User Contributed Perl Documentation for constant::defer β€” aka constant subs whose value gets calculated LATER. it's giving "i'll do it when i need to" and honestly? relatable. πŸ¦‹


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

periodt. that's the whole vibe. πŸ’œ


πŸŽ€ DESCRIPTION πŸŽ€

so constant::defer makes a subroutine that, the first time you call it, runs whatever code you gave it to figure out its value. and then literally every time after that? it just hands you back that same value. like a constant. ✨ The value code gets discarded once it's run, which means it's free to be garbage collected. bye code, you served your purpose, we love you, we release you 🫢

deferring a calculation is the move when the work might be a LOT or the result might be BIG, but you only need it sometimes, or only way later in the program run. And if you never need it? The value code never runs at all. girl never even showed up. πŸ’€

ngl a deferred constant is generally not inlined or folded (peep "Constant Folding" in perlop for that) because it's not a single scalar value. But in the current implementation, a deferred constant becomes a plain constant after the first use, so it may inline etc. in code compiled after that (go look at "IMPLEMENTATION" below πŸ‘‡).

also there's a whole complete sample program in examples/simple.pl in the constant-defer source code, if you want to see it living its life.

πŸ’« Uses πŸ’«

here are the typical ways people use this. so good.

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

if ($option) {
  print "s=", SLOWVALUE, "\n";
}
  • A shared object instance that gets created when needed and then re-used forever after, iconic behaviour:
use constant::defer FORMATTER =>
      sub { return My::Formatter->new };

if ($something) {
  FORMATTER()->format ...
}
  • The value code might load requisite modules too, which again defers THAT until it's actually needed. no cap:
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. Just remember to have an empty or undef return value, so you don't keep the last expression result alive forever (that's an eternal hostage situation, we don't do that here πŸ™ˆ):
use constant::defer MY_INIT => sub {
  many lines of setup code ...;
  return;
};

sub new {
  MY_INIT();
  ...
}

πŸ¦‹ IMPORTS πŸ¦‹

bestie there are no functions as such β€” everything happens through the use import. it's all vibes and import magic, no middleman.

  • use constant::defer NAME1=>SUB1, NAME2=>SUB2, ...; β€” the parameters are name/subroutine pairs. For each one, a sub called NAME gets created, and it runs the given SUB the first time its value is needed.

NAME defaults to the caller's package, or you can hand over a fully qualified name. Just remember that bareword stringizing of => doesn't act on a fully qualified name, so add quotes in that case. quotes are your friend, fr fr:

use constant::defer 'Other::Package::BAR' => sub { ... };

For compatibility with the constant module, a hash of name/sub arguments is accepted too. But constant::defer doesn't need this style, since there's only ever one thing (a sub) following each name. slay either way:

use constant::defer { FOO => sub { ... },
                      BAR => sub { ... } };

# works without the hashref too
use constant::defer FOO => sub { ... },
                    BAR => sub { ... };

🌈 MULTIPLE VALUES 🌈

plot twist: the value sub can return multiple values, which makes an array style constant sub. we love a versatile queen. πŸ’…

use constant::defer NUMS => sub { return ('one', 'two') };

foreach (NUMS) {
   print $_,"\n";
}

The value sub is always run in array context, for consistency, no matter how the constant is used. And the return from the new constant sub is an array style:

sub () { return @result }

okay so if the value sub was a list-style return like NUMS 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. Wild, right?? A multi-value constant won't normally be used in scalar context though, so the difference shouldn't arise. The array style is easier for constant::defer to implement and is the same as what the plain constant module does. consistency king. πŸ‘‘


🌸 ARGUMENTS 🌸

If the constant is called with arguments, then those arguments get 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, ngl.

A cute use for a class method style is making a "singleton" instance of the class. See examples/instance.pl in the constant-defer source code for a complete program. ✨

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

Some care might be needed if you let a subclass object become the parent INSTANCE, though if a program only ever used the subclass then that might in fact be desirable. no rules, just vibes. πŸ¦‹

Subs created by constant::defer always have prototype (), which ensures they always parse the same way. The prototype has no effect when called as a method like above, but if you want to make a plain call with arguments, then use & to bypass the prototype (see perlsub).

&MYCONST ('Some value');

πŸ’œ IMPLEMENTATION πŸ’œ

Currently constant::defer creates a sub under the requested name, and when it's called it replaces that with a new constant sub, the same as use constant would make. This is compact and means later loaded code might be able to inline it. lowkey efficient bestie.

It's fine to keep a reference to the initial sub, and in fact that happens quite normally if you're importing into another module (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. one and done, no reruns. πŸ™…β™€οΈ

The jump is currently done by a goto to the new coderef, so it's a touch slower than the new constant sub directly. A spot of XS would no doubt make the difference negligible, perhaps to the point where there'd be no need for a new sub β€” you'd just have the initial transform itself. And if the new form looked enough like a plain constant, it might inline in later loaded code. πŸ‘€

For reference, Package::Constants (as of its version 0.06) considers constant::defer subrs as constants, both before and after the first call which runs the value code. Package::Constants just looks for prototype sub foo () { } functions, so any such subr rates as a constant. certified constant. πŸ’…


πŸ”₯ OTHER WAYS TO DO IT πŸ”₯

There's many ways to do "deferred" or "lazy" calculations. here's the whole lineup, no gatekeeping:

  • Memoize makes a function repeat its return. Results are cached against the arguments, so it keeps the original code, whereas constant::defer discards after the first run.
  • Class::Singleton and its friends make a create-once My::Class->instance method. constant::defer can go close with the fakery shown under "ARGUMENTS" above, though without a has_instance() to query.
  • Sub::Become offers some syntactic sugar for redefining the running subroutine, including to a constant.
  • Sub::SingletonBuilder can create an instance function for a class. It's designed for objects and so doesn't allow 0 or undef as the return value.
  • Sub::StopCalls mangles the code in its caller to put a value as a constant there. The effect is to run a function just once at each caller location, replacing it with the return value, though the function can also choose to constant-ize only sometimes, based on circumstances, arguments, etc.
  • A $foo scalar variable can be rigged up to run code on its first access. Data::Lazy uses a tie. Scalar::Defer and Scalar::Lazy use overload on an object. Data::Thunk optimizes out the object from Scalar::Defer after the first run. Variable::Lazy uses XS magic (removed after the first fetch) and some parsing for syntactic sugar.

The advantage of a variable is that it interpolates in strings. The disadvantages are it won't inline in later loaded code; bad XS code might bypass the magic; and package variables aren't very friendly when subclassing. 😭

  • Object::Lazy and Object::Trampoline rig up an object wrapper to load and create an actual object only when a method is called, dispatching to it and replacing the caller's $_[0]. The advantage is you can pass the wrapper object around, etc., deferring creation to an even later time than a sub or scalar can.
  • Object::Realize::Later, Class::LazyObject and Class::LazyFactory 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.
  • once.pm sets up a run-once code block, but with no particular return value and not discarding the code after run.
  • Class::LazyLoad and deferred.pm load code on a class method call such as object creation. They're mainly to defer module loading rather than calculation of a particular value.
  • Tie::LazyList and Tie::Array::Lazy makes array elements calculated on-demand from a generator function. Hash::Lazy does a similar thing for hashes. Tie::LazyFunction hides a function behind a scalar; its laziness is in the arguments which are not evaluated until used.

πŸ‘‘ SEE ALSO πŸ‘‘

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, Sub::StopCalls, Object::Lazy, Object::Trampoline, Object::Realize::Later, once, Class::LazyLoad, deferred


⭐ HOME PAGE ⭐

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

okay bestie, legal era incoming, but it's literally the shortest part so we slay πŸ’…

Copyright 2009, 2010, 2011, 2012, 2015 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 of the License, or (at your option) any later version. so like, v3 or newer, your call, no pressure 🫢

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. 😭 yeah that's the all-caps bit, it's giving "we're rooting for you but we are NOT liable". 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/>. πŸ‘‘


and that's the whole page, bestie!! no cap, that's the end of constant::defer. the source is perl v5.36.0, dated 2022-10-16, and it lives at constant::defer(3pm). go forth and defer your constants responsibly βœ¨πŸŽ€πŸŒΈ

πŸ“¦ where this page comes from