Re: Idea / preRFC - return value of require
[email protected] ("Smylers " via perl5-porters) Thu, 12 Feb 2026 15:44:33 +0100 (CET)
| Newsgroups | perl.perl5.porters |
|---|---|
| Message-ID | <[email protected]> |
Branislav Zahradník writes:
> I will be fine with expression `require :cached Foo` (naming is not
> important, behaviour is) ... Yes, I can do:
>
> sub { require Foo; Foo->value }
>
> but that is additional number of tokens I want to avoid.
It's additional tokens that clarifies your intent, rather than being
invisible and magical, and isn't much more than adding :cached.
Is this something that you can see people who aren't you making enough
use of that it's worth adding this behaviour into the core language?
Your initial example was:
sub build_reader ($from, @arguments) {
state $build_from_map = {
data => sub { require Build::From::Scalar },
file => sub { require Build::From::File },
zip => sub { require Build::From::Zip::File },
};
I'd probably write that as something like:
sub build_reader ($from, @arguments) {
require Build::From::Loader;
state $build_from_map = {
data => sub { Build::From::Loader->('Scalar' },
file => sub { Build::From::Loader->('File' },
zip => sub { Build::From::Loader->('Zip::File' },
};
where Build::From::Loader is a module that does the right thing.
or even:
sub build_reader ($from, @arguments) {
require Build::From::Loader;
state $build_from_map = {
data => _builder('Scalar' },
file => _builder('File' },
zip => _builder('Zip::File' },
};
where _builder() is a local function that loads the required module and
then invokes ->Value on it (or whatever).
That's doable now, and backwards compatible.
> On Thu, 12 Feb 2026 at 15:18, Johan Vromans <[email protected]> wrote:
>
> On Thu, 12 Feb 2026 14:35:52 +0100, Branislav Zahradník wrote:
>
> > sub foo { return require My::App::Foo; }
>
> How about
>
> > sub foo { return state $p = require My::App::Foo; }
>
> How it will behave when "require My::App::Foo" is executed by other
> code before calling `sub foo`?
The same as when C<require My::App::Foo> is executed before
C<require :cached My::App::Foo>, presumably?
Without :cached, this feature would be completely invisible and
backwards-incompatible. With :cached, it would require updating
everywhere that loads the module — in which case they could instead be
updated to use another module or function which has the desired
behaviour.
Smylers