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


In reply to Re: Where in a package should 'use' be called? by davido
in thread Where in a package should 'use' be called? by stevieb

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.