Why is using a statement in a routine applied 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 sub is applied globally.

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

+7
scope module perl use
source share
2 answers

use Module; has two effects.

The first is to load the module. Obviously, this has a global effect. I would not want the module to load several times if it is used by more than one other module.

The second call is to call the import method. For most modules, this serves to export characters to the caller namespace so that these functions can be called without specifying their full package name. This, obviously, affects not only some part, since no one gives everyone under their own namespace. But it really is up to you.

Some import module methods, however, do something completely different. They change the way code is compiled in the lexical domain in which the directive is present. They are called pragmas. use strict; - an example of one. It makes sense to use these modules in the subsection. However, using use HTML::TreeBuilder::XPath; in sub does not make sense.

+6
source share

This is what perldoc is :

Since use takes effect at compile time, it does not take into account normal control over the flow of compiled code. In particular, using a function inside a false conditional branch does not prevent its processing.

Unfortunately, it does not explain why it is designed that way. Possible reasons may include:

  • Perl gives a lot of freedom in many cases (TIMTOWTDI)
  • use inside a routine might seem like you really want to use the module only in a certain place (even if it loads worldwide).
  • If you (re) move a particular routine (which contains use ) later, you don’t have to worry about removing unused use from other places, such as the top of your script
  • ...

Despite the fact that these ideas may seem plausible, I would not load modules into routines, because it is much clearer of them all in one place, and not scattered everywhere?

+4
source share

All Articles