Wednesday, April 7, 2010

including/Using/Require Perl Modules in Program

There are many ways to include modules/packages in your program.

Use Module;

Or
Use Module List;

Which is exactly equivalent to

    BEGIN { require Module; import module; }
                   or
    BEGIN { require Module; import Module List; }
                   or
    require "Module.pm";
    import Module;

All perl modules have extensions.pm, use assumes this so you don't have to spell it out explicitly as "Modules.pm" instead you can say use Module;

Following two statements:

require Module;
require "Module.pm";

differ from each other. In first case, any double colon ( my::module) will be translated to  system's directory separator e.g."/", while in second case you will have to give module name with path literally.


With "require" one can get into following problem:
require myModule;
$some = myModule::somefunc();  # Need to make myModule:: accessible

use myModule;               # Import Names from myModule
$some = somefunc();

require myModule;
$some=somefunc();  # Error: No main::somefunc(),    so be careful in this case. solution is as follow

Above problem can be solved as following:
require "myModule.pm";
import myModule;
$some=somefunc();

Command Line inclusion
For including module from command line use following command:
C:\>perl -MmyModule myprogram.pl

For more information on -M switch check perlrun in perldoc
For more information on this refer to this link.
or check in chapter 11. modules in Perl Programming.

No comments:

Post a Comment