|more useful options|
Re: 'require/use' scopingby brian_d_foy (Abbot)
|on Jan 29, 2008 at 15:26 UTC||Need Help??|
[ Whenever someone asks you the difference between require and use, point them to the use entry in perlfunc. Not only will they get the right answer, but they'll learn how to use the docs. In this case, the OP wants to know about what require does and how it does it. Again, perlfunc has the answer. :)]
Packages or namespaces are not scopes! This week I've seen a few people mention that, but it's not true and I don't know where people ever see that. Scopes are either blocks of code or the file, which has an implicit scope around all of its contents. The package pragma is scoped, but any symbol table work it does is not.
These two are equivalent and there's nothing else special going on. It's not just a run-/compile-time thing. The use also implies an import.
Curiously, the answer in perlfaq8 on "What's the difference between use and require" is crap, so now I must go fix it. And so it has come to pass:
What's the difference between require and use?
Perl runs require statement at run-time. Once Perl loads, compiles, and runs the file, it doesn't do anything else. The use statement is the same as a require run at compile-time, but Perl also calls the import method for the loaded package. These two are the same:
However, you can suppress the import by using an explicit, empty import list. Both of these still happen at compile-time:
Since use will also call the import method, the actual value for MODULE must be a bareword. That is, use cannot load files by name, although require can:
See the entry for use in perlfunc for more details.
Now, the other part of the OP's question is what require is actually doing. Again, it's right in perlfunc. This code is directly from the entry on require and shows exactly what you would have to do on your own to recreate its behaviour:
That little snippet is already assuming that a bareword has been turned into a filename, and doesn't do portable path construction, but it's the mechanics that count. Notice the do to actually run the code.
brian d foy <email@example.com>
Subscribe to The Perl Review