And what would you (they) do if a module is subsequently needed in another subroutine in the same file?
Unless the other subroutine is in a different package it doesn't matter whether it also "use"s the module or not, it's loaded and will be available (I think you are probably aware of this, just putting it in as clarification). See this example
#!/usr/bin/perl
use strict;
use warnings;
mainsub();
secsub();
thirdsub();
Frob::fourthsub();
sub mainsub {
use Data::Dumper;
}
sub secsub {
my $r = "secsub";
print Dumper $r;
}
sub thirdsub {
use Data::Dumper;
my $r = "thirdsub";
print Dumper $r;
}
package Frob;
sub fourthsub {
my $r = "thirdsub";
print Dumper $r;
}
Output:
Name "Frob::Dumper" used only once: possible typo at useuse.pl line 31
+.
$VAR1 = 'secsub';
$VAR1 = 'thirdsub';
print() on unopened filehandle Dumper at useuse.pl line 31.
IMO there are several very good reasons not to put "use" into a subroutine (or other block) but rather at the top of a package:
- It obfuscates which modules you are using, one has to hunt through the entire file to find out which modules are loaded.
- To make this more confusing, if the file contains multiple packages one needs to limit ones search to just that package, which requires thought instead of just editor-fu
- Programmers unfamiliar with the compile-time loading property of "use" might be surprised/confused about symbols from that module being available in other subroutines
- Conversely, programmers who come to rely on just sticking "use" anywhere in a file might be surprised that it's not available in a different package (this goes for putting "use" underneath the package declaration as well, but at least here the ordering gives a hint that the two are relevant to each other).
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|