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

I'm writing a module (package), and I need to use another module, but not until a specific subroutine gets called (in this case, a sub that *always* is called). use is executed at compile-time, so where in a sub-only (ie. non-executable) module is the best place to require/include ie. use this external module?

Is it wise to put the use at the top of the module so it is clearly visible upon first glance, or in the sub that needs it so it's identified that we need it here while reviewing the code?

Replies are listed 'Best First'.
Re: Where in a package should 'use' be called?
by davido (Cardinal) on Sep 28, 2015 at 02:58 UTC

    Both are useful. Typically people place the "use" statements at the top, and if necessary, document why. You can place the use almost anywhere though. However, keep in mind that since use has a compile-time component to it, its effects are not constrained to the scope of whatever sub calls use:

    use feature qw/say/; say "Outside of sub: ", sum(1..10); say "Inside of sub: ", foo(1..10); sub foo { use List::Util qw(sum); return sum(@_); }

    As you can see, both calls have access to sum

    For this reason, you will sometimes see code that needs to conditionally load a module use require. This won't automatically import the names that the target module exports, you would then have to call that module's import. Or if you want to keep your namespace clean, just use fully-qualified names.

    Another way to conditionally load a module is with the if module.


    Dave

Re: Where in a package should 'use' be called?
by u65 (Chaplain) on Sep 28, 2015 at 00:26 UTC

    As you say, where you use a module matters not in Perl 5 and I have done it both ways over past years. But this year, since I am now cognizant of Perl 6's module scoping rules, I put the module use statement in a subroutine unless it is to be used in more than one scope.

      Thanks u65... a few years ago, I toyed with Perl6 because moritz's at-the-time PM sig tested my patience (you can see my very basic p6 'testing' here). After getting set up, I appreciated quite a few things (and was upset due to others) but I especially liked calling a method on a literal, eg: say 25.WHAT :). Up until now, I did not know that use was kept within lexical (ie. block) scope and not compile-time in P6. Is this true?

      For now, I'm looking specifically for Perl5 best practice.

Re: Where in a package should 'use' be called?
by Anonymous Monk on Sep 28, 2015 at 11:50 UTC
    All at top of the module, in any language.