Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

When should we use "use" and when "require" and when "AUTOLOAD" in perl ? I need a thumb rule for this.

like image 919
Mandar Pande Avatar asked Feb 12 '12 14:02

Mandar Pande


1 Answers

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.

like image 145
DVK Avatar answered Nov 10 '22 08:11

DVK