When should you use "use" and "require" and "AUTOLOAD" in perl [good programming practice]?

When should we use "use" and "require" and "AUTOLOAD" in perl ? To do this, I need a thumb rule.

+7
source share
1 answer

use equivalent to BEGIN { require Module; Module->import( LIST ); } BEGIN { require Module; Module->import( LIST ); }

So, the main difference is that:

  • Usage is used at compile time.

  • Use automatically calls the import routine (which can do anything, but is mainly used to export identifiers to the caller's namespace)

  • use stamps if the module cannot be loaded (missing / compile error)

As such:

  • If you need to dynamically load modules (for example, determine which module will be loaded based on command line arguments), use require .

  • In the general case, when you need to precisely control when a module is loaded, use require ( use will load the module immediately after the previous use or BEGIN , at compile time ).

  • If you need to somehow get around the calling module import() routines, use require

  • If you need to do something clever, how to handle loading errors (missing module, the module cannot compile), you can wrap require in an eval { } statement, so the whole program isn’t just going to die.

    You can simulate this using use , but in a rather elegant way (capturing the die signal in the early BEGIN block should work). But it is better eval { require } .

  • In all OTHER cases, use

I did not consider AUTOLOAD as another star. Its use occurs when you want to rewrite subroutine calls that you did not import into your namespace.

+16
source

All Articles