Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Is it ok to require a module in a sub or method?

by leocharre (Priest)
on Sep 11, 2007 at 12:08 UTC ( #638343=perlquestion: print w/replies, xml ) Need Help??

leocharre has asked for the wisdom of the Perl Monks concerning the following question:

Okay. I've got something that's been bugging me. And I need to get some feedback on this or I will not be able to move on with my day. I had some large modules, and I realized they did not need to load all, so .. instead of
use Cwd; sub iamin { return cwd; }
I do
sub iamin { require Cwd; return Cwd::cwd(); }
So I just require the modules I want if needed.

So, what if I am calling the sub or method a million times? Is perl just skipping over the require line because it's been already loaded? Or is there a little something going on that would eventually cause a performance hit?

Replies are listed 'Best First'.
Re: Is it ok to require a module in a sub or method?
by merlyn (Sage) on Sep 11, 2007 at 12:09 UTC
    The require checks %INC, and if it's already there, is a no-op. So feel free... it's just a hash lookup on every time but the first.
Re: Is it ok to require a module in a sub or method?
by ikegami (Pope) on Sep 11, 2007 at 12:30 UTC

    Off the top of my head, I came up with the following problems:

    • Some errors that would occur at script start-up now occurs when the function is called instead.
    • The prototypes of functions in the module will get ignored.
    • CHECK blocks in the module won't get executed and will issue a warning.
    • INIT blocks in the module won't get executed and will issue a warning.
    • Packagers such are PAR might not notice the module. (I'm not sure how they work.)
Re: Is it ok to require a module in a sub or method?
by grinder (Bishop) on Sep 11, 2007 at 12:41 UTC

    Bearing in mind the caveats noted by ikegami, you can also use autouse the module at the top of your program, to defer the loading of the module until if and when it is called.

    This means that your program doesn't need the make-work "should I load the module before I use it?" code. There are also the AnyLoader and AutoLoader modules which do roughly the same thing, but I am less familiar with them.

    • another intruder with the mooring in the heart of the Perl

Re: Is it ok to require a module in a sub or method?
by almut (Canon) on Sep 11, 2007 at 13:55 UTC

    Just one other thing. In case the module you're requiring does have an import() routine that's doing something meaningful, you might want to call it manually after the require. (Doing require Module; is more like use Module (); (ignoring the difference, the implicit BEGIN, for the moment). This might not always be what you want.) However, in case you do need to call import manually, you'll probably want to devise some mechanism (e.g. checking %INC) to avoid having it execute on every invocation of you sub ... (i.e. exactly the issue you were worried about).

    On the other hand, if the module is just inheriting Exporter's import method (as many modules do), this is probably not much of an issue, as you can always call the routines fully qualified (instead of having them imported into your namespace).

    In other words, it depends... but it might be something worth thinking about — in particular if things are not behaving as expected :)

Re: Is it ok to require a module in a sub or method?
by shmem (Chancellor) on Sep 11, 2007 at 17:54 UTC
    That's fine. Bear in mind, though, that requiring a module at runtime may change the overall behaviour of your code. After requiring a module, the namespace of that module is globally visible, and requiring it may change the inheritance chain (?). If the runtime-required modules define symbols that are deferred to be handled via AUTOLOAD by modules which have the current (requiring module) in its @ISA, strange and hard to debug things might happen.

    I feel at ease only if my overall code architecture is built upon runtime loading, or if I require modules as a last resort, e.g.

    sub bail_out { require Carp; Carp::confess(@_); }

    I'd use a module like Cwd up front, btw. Consider AutoLoader. Likewise, you can define a namespace of a module without actually loading it, and declare stubs for methods/subroutines like

    package Cwd; sub cwd; package main; # or whatever module you are in ...
    which will be defined only after the subroutine that requires the module has been called.
    This is a dark corner I have to lighten up for myself, yet.


    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re: Is it ok to require a module in a sub or method?
by nothingmuch (Priest) on Sep 16, 2007 at 23:10 UTC
    prefork might be helpful, giving a similar effect when in a non forking environment, but preloading before a fork.
    zz zZ Z Z #!perl

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://638343]
Approved by ikegami
Front-paged by grinder
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2021-05-18 21:45 GMT
Find Nodes?
    Voting Booth?
    Perl 7 will be out ...

    Results (186 votes). Check out past polls.