Another question got me thinking about different methods of code reuse: use
vs. require
vs. do
I see a lot of posts here where
There is a major preference for using use
, because it happens at an earlier state BEGIN {}
during compilation, and the errors tend to be propagated to the user at a more appropriate time. It also calls the sub import {}
function which gives the caller control over the import process. This is something that is heavily used. You can get the same effect, by calling the specific namespace's import
, but that requires you to know the name of the namespace, and the file, and to code the call to the subroutine... which is a lot more work. Conversely, use
, just requires you to know the namespace, and then it requires the file with the matching namespace -- thus making the link between namespaces and files less of an conscious to the user.
Read perldoc -f use, and perldoc -f require, for more information. Per perldoc -f use:
use
is the same as BEGIN { require Module; Module->import( LIST ); }
Which is just a lot more ugly.