in reply to Re: Autovivification with require
in thread Autovivification with require

From the documentation for require

In other words, if you try this:

require Foo::Bar; # a splendid bareword
The require function will actually look for the Foo/Bar.pm file in the directories specified in the @INC array, and it will autovivify the Foo::Bar:: stash at compile time.

But if you try this:
my $class = 'Foo::Bar'; require $class; # $class is not a bareword #or require "Foo::Bar"; # not a bareword because of the ""
The require function will look for the Foo::Bar file in the @INC array and will complain about not finding Foo::Bar there. In this case you can do:
eval "require $class";
or you could do
require "Foo/Bar.pm";
Neither of these forms will autovivify any stashes at compile time and only have run time effects.


This seems to imply that there is some implicit advantage of one form over another because one autovivifies and the other does not - it was this part of the documentation that gave rise to my question...

Replies are listed 'Best First'.
Re^3: Autovivification with require
by Fletch (Bishop) on Nov 20, 2020 at 16:34 UTC

    I believe what that usage is trying to highlight is that if you have a bareword use Foo::Bar; or require Foo::Bar; then at compile time perl knows that there is a Foo::Bar package and that it will make some kind of entries in the package stash (*Foo::Bar and/or %Foo::Bar::) before continuing to compile subsequent code (which may affect things like "variable only used once" warnings). Also in the use case the import method would be called at compile time which would then have side effects (e.g. inserting entries in the calling package's namespace).

    If you use the string version the code in the file pulled in won't be compiled until the require statement is actually executed which will be after everything else has already compiled. It affects when some things happen; whether that's an "advantage" or not depends on what you're expecting to happen.

    ## Poor example: Cwd pulled in with use so %Cwd:: is fully populated $ perl -E 'say qq{Cwd stash keys: }, scalar %Cwd::; use Cwd; say qq{Cw +d stash keys after use: }, scalar %Cwd::; say qq{Config stash keys: } +, scalar %Config::;require "Config.pm"; say qq{Config stash keys afte +r requiire: }, scalar %Config::;' Cwd stash keys: 39 Cwd stash keys after use: 39 Config stash keys: 1 Config stash keys after requiire: 20

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.