Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does use statement in sub apply globally?

use WWW::Mechanize;
$mech = new WWW::Mechanize;
$mech->get("http://www.google.com");
$html = HTML::TreeBuilder::XPath->new_from_content($mech->content);
sub test
{
    use HTML::TreeBuilder::XPath;
}

The above code compiles, so the use statement in the sub is being applied globally.

Why does perl do this? It doesn't make any sense.

like image 990
CJ7 Avatar asked Sep 22 '16 01:09

CJ7


1 Answers

use Module; has two effects.

The first is to load the module. Obviously, that has a global effect. One wouldn't want a module to be loaded multiple times if more than one other module uses it.

The second is to call the module's import method. For most modules, this serves to export symbols to the caller's namespace so those functions can be called without qualifying them with a full package name. This obviously affects more than just some sub since noone gives each sub its own namespace. But that's really up to you.

Some module's import method, however, do something quite different. They alter how code is compiled in the lexical scope in which the directive is present. These are called pragmas. use strict; is an example of one. It makes sense to use these modules in a sub. Using use HTML::TreeBuilder::XPath; in a sub, however, makes no sense.

like image 90
ikegami Avatar answered Nov 12 '22 02:11

ikegami