Herong's Tutorial Notes on Perl - Part A
Dr. Herong Yang, Version 4.09

perlmod - Perl Modules

Part:   1   2  3  4 

This chapter describes:

  • How to include source codes from other files.
  • How to define and use name spaces.
  • How to define special subroutines for compilation and execution processes.
  • How to define and use Perl modules.
  • A simple sample module - CalendarModule.pm.

Including Source Codes from Other Files

There are many reasons for including source code from other files. One of them is that you have a section of code that is identical to many of your programs, and you don't want to copy it to each of your programs. Examples of this type of shared code are default values of controlling variables and common subroutines.

There are two simple ways to include source code from other files:

1. Using do() function to include and execute the source code of the specified file.

  • It will search the file in the @INC path name array.
  • It will add an entry to %INC with file name as key and full path name as value.
  • It will return the last expression executed. So to make the calling program happy, you should put a dummy expression like "1;" at the end of the include file.

To try this out, I wrote the following file for other programs to include, MyDoLib.inc,

#- MyDoLic.inc
#- Copyright (c) 1995 by Dr. Herong Yang
#
   $author = "Herong Yang";
   print("Printing from MyDoLib.inc...\n");
sub myDoSub {
   print("Printing from myDoSub()...\n");
}
1;

Here is the calling program, IncDoTest.pl,

#- IncDoTest.pl
#- Copyright (c) 1995 by Dr. Herong Yang
#
   do("MyDoLib.inc");
   print("Printing from IncDoTest.pl...\n");
   print("Author = $author\n");
   &myDoSub();
   exit;

Output looks good:

Printing from MyDoLib.inc...
Printing from IncDoTest.pl...
Author = Herong Yang
Printing from myDoSub()...

2. Using require() function to include and execute the source code of the specified file. require() will do everything do() does, and is smarter than do() in the following areas:

  • It will check %INC to see if the specified file has already being include. If so, do nothing and return 1. Otherwise, continue.
  • It will add an entry to %INC with file name as key and full path name as value, only if the execution was successful.

To try this out, I wrote another include file, MyRequireLib.inc,

#- MyRequireLib.inc
#- Copyright (c) 1995 by Dr. Herong Yang
#
   $author = "Dr. Herong Yang";
   print("Printing from MyRequireLib.inc...\n");
sub myRequireSub {
   print("Printing from myRequireSub()...\n");
}
1;

(Continued on next part...)

Part:   1   2  3  4 

Dr. Herong Yang, updated in 2006
Herong's Tutorial Notes on Perl - Part A - perlmod - Perl Modules