<?xml version="1.0" encoding="windows-1252"?>
<node id="670572" title="Re^2: Code style advice: where to put &quot;use&quot; statements?" created="2008-02-27 05:20:04" updated="2008-02-27 00:20:04">
<type id="11">
note</type>
<author id="237051">
tirwhan</author>
<data>
<field name="doctext">
&lt;blockquote&gt;&lt;i&gt;And what would you (they) do if a module is subsequently needed in another subroutine in the same file?&lt;/i&gt;&lt;/blockquote&gt;
&lt;p&gt;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 [BrowserUK|you] are probably aware of this, just putting it in as clarification). See this example&lt;/p&gt;
&lt;c&gt;
#!/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;
}
&lt;/c&gt;
Output:
&lt;c&gt;
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.
&lt;/c&gt;
&lt;p&gt;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:&lt;/p&gt;
&lt;ul&gt;&lt;li&gt;It obfuscates which modules you are using, one has to hunt through the entire file to find out which modules are loaded.&lt;/li&gt;
&lt;li&gt;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&lt;/li&gt;
&lt;li&gt;Programmers unfamiliar with the compile-time loading property of "use" might be surprised/confused about symbols from that module being available in other subroutines&lt;/li&gt;
&lt;li&gt;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).&lt;/li&gt;&lt;/ul&gt;
&lt;div class="pmsig"&gt;&lt;div class="pmsig-237051"&gt;
&lt;br&gt;&lt;i&gt;All dogma is stupid.&lt;/i&gt;
&lt;/div&gt;&lt;/div&gt;</field>
<field name="root_node">
670475</field>
<field name="parent_node">
670482</field>
</data>
</node>
