Apologies if this question isn’t appropriate for StackOverflow. I suspect the answer is largely a matter of opinion (unless one of the style guides has a recommendation).
I have code that looks something like this
use File::Temp;
sub foo {
...
}
sub bar {
...
}
sub baz {
my $fh = tempfile();
...
}
baz is the only subroutine that uses File::Temp, and I’m not using AutoLoader. Is it reasonable to put the use declaration inside baz, or should I leave it at the top of my script?
Since (as chepner said), there is no difference technically, it really is a matter of style.
The pros of putting then all on top:
Clear at first glance what all the direct module dependencies are
Easier to maintain – if you need to move around code using the library, you don’t need to remember to move the library.
Please note that the same exact logic also applies to variable declarations, but in that case, the scoping concerns severely trump the “remember to move the declaration” concerns and therefore you should declare variables in the innermost possible scope as close to where they are used as possible.
For esoteric cases where your own code contains complicated logic in
BEGIN{}blocks that depends on all the libraries being loaded (e.g., call a specifically named method from ALL loaded libraries – which I have done) – you will have a bug if some library’susecall is AFTER thatBEGIN{}blockThe cons of putting them all on top: