When should we use "use" and when "require" and when "AUTOLOAD" in perl
? I need a thumb rule for this.
use
is equivalent to BEGIN { require Module; Module->import( LIST ); }
So, the main difference is that:
Use is used at compile time
Use automatically calls import subroutine (which can do anything but mostly used to export identifiers into caller's namespace)
use dies if the module can not be loaded (missing/compile error)
As such:
When you need to load modules dynamically (for example, determine which module to load based on command line arguments), use require
.
In general, when you need to precisely control when a module is loaded, use require
(use
will load the module right after the preceding use
or BEGIN
block, at compile time).
When you need to somehow bypass calling module's import()
subroutine, use require
When you need to do something smart as far as handling load errors (missing module, module can't compile), you can wrap the require
into an eval { }
statement, so the whole program doesn't just die.
You can simulate that with use
but in rather in-elegant ways (trapping die
signal in an early BEGIN
block should work). But eval { require }
is better.
In all OTHER cases, use use
I didn't cover AUTOLOAD as that's a different beastie. Its usage is in cases when you want to intercpt calls to subroutines that you haven't imported into your namespace.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With