|Do you know where your variables are?|
Use and Require - making an informed choice.by g0n (Priest)
|on Jan 30, 2006 at 11:11 UTC||Need Help??|
This is a relatively simple issue, but one that I've never seen discussed, so I thought I'd bring it up.
My default position when I use external modules is:
(but then I have quite a lot of 'C-ish' habits). If I have a particular need to use 'require' then I will, but normally 'use' is the norm and 'require' the exception. The important distinction between 'use' and 'require' is that 'use' is called at compile time, and 'require' at run time (plus, 'use' calls the modules import method implicitly). A few days ago I came across a design & implementation issue that makes this distinction very important.
I have a module that contains a range of utility functions, which I use with varying frequency. Two of the rarely used functions rely on the ability of Data::Dump::Streamer to serialise coderefs, but I don't use them very often. Since 'require' is executed at run time, I can put the require Data::Dump::Streamer; line in the functions that need it, rather than a 'use' at the top of the module, and the code compiles and runs fine on my PDA without DDS installed, as long as I don't want to use the 'save' or 'load' functions that depend on DDS.
So, the factors for choosing between the two seem to me to be as follows:
If the answers are 'no', then it seems to me it would be worth importing the module with 'require' where it's needed. The point of the third is that this only really applies to things like utility scripts & modules used across multiple machines by informed users (like yourself) - if you are writing a deployed application or an unattended script you will want the dependencies to be resolved.
Can anyone suggest other factors influencing the choice?
Update: There will also be a speed of execution hit at the time that the module is being imported, so I guess that's another factor. But then, restricting 'use' to modules you really need should reduce compile time, leaving the overhead of importing a module with 'require' to when you actually need it.
Update: Two other issues raised by zentara: require will accept a string instead of a namespace, so permits import of non ~.pm files, and also require can present unexpected collisions with global variables.
"If there is such a phenomenon as absolute evil, it consists in treating another human being as a thing."
John Brunner, "The Shockwave Rider".