Idea / preRFC - return value of require
[email protected] (Branislav Zahradník)
| Newsgroups | perl.perl5.porters |
|---|---|
| Message-ID | <CAB=rbOm23nw++n=9fD93dU3t_=n18oygSpV=GKmWLjTysRpLXw@mail.gmail.com> |
Hi,
Recently I had an idea how to improve some of my code,
resulting in following preRFC.
What is your opinion on usability?
Let's start with "I want this code" and then "what should be modified to
make it work".
Code:
```
sub foo { return require My::App::Foo; }
foo->new (...);
```
Intended usage:
```
package Foo;
__PACKAGE__;
package Foo {
__PACKAGE__;
}
```
Expectation:
- first call of function will load specified module
- subsequent call of function will always return same value as first call
Current behaviour:
- subsequent call returns value true if require was successful
- if package-block is used, it doesn't return value of last statement of
block but only logical true/false
Changes to be implemented:
- require should cache "returned value" instead of just status
- document possible side effects
- package-block should evaluate as it's last expression
Some babbling:
- feature will be become handy when require will support dynamic loading,
eg like:
```
require :module $plugin;
```
- usage in dispatch map
```
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 },
};
$build_from_map->{$from}->new (@arguments);
}
```
- imported module can provide reasonable data, for example returning
coderef:
```
package Foo { ...; \ &foo }
# example usage:
$ENV{API_V1_ENABLED} &&
under q (/api/v1) => sub {
get q (/user/list) => require My::App::Operation::User::List;
get q (/user/:user_id) => require My::App::Operation::User::Fetch;
};
$ENV{API_V2_ENABLED} &&
under q (/api/v2) => sub {
get q (/users) => require My::App::Operation::User::List;
get q (/user/:user_id) => require My::App::Operation::User::Fetch;
};
```