ACCC Home Page ACADEMIC COMPUTING and COMMUNICATIONS CENTER
Accounts / Passwords Email Labs / Classrooms Telecom Software Computing and Network Services Education / Teaching Getting Help
 
Seminar - Perl II
0. Contents 1. Intro 2. Sources 3. References 4. Packages 5. Classes
6. Ties & DBM 7. Typeglobs 8. CGI 9. Security 10. Example  

Packages / Modules

   
 
     
Packages
 

What with all the third part libraries for perl, there needs to be a sane way to manage names. Suppose two different packages use the variable $count. Chaos! Unless, of course, these variables are somehow made local.

The package statement allows different libraries to keep their own space. Perl allows any statement to use any package. So privacy is not enforced, but don't go violating it unless you know what you are doing.

Every global variable lives in a package. If you don't explicitly declare the package, then the default is main:: or just :: for short.

You can refer to a variable in a package explicitly, such as $mypack::count. (This is the $count variable in the mypack package, and is not written mypack::$count). Or you can use the package statement to reset the default package from that point on. (Well, at least until the next package statement, or end of file.)

One caveat. The special variables, such as $_ or $/, are always in main::, no matter what. Also note that package variables cannot be my() variables.

 $count = 0;
 package mypack;
 $count = 1;
 print $main::count;    # 0
 print $count;          # 1
 package main;
 print $count;          # 0
 
     
Modules
 

A perl module is just a way to arrange a library to make it easy to use. It has:

  • Code that uses a package.
  • A filename like Package.pm
  • (Optionally) a subroutine named export. The Exporter.pm module provids a default subroutine that is used to selectively add some subroutines to the package that use's the module.
  • Note that the module must in a directory in @INC. You can change @INC with the use lib statement at compile time.
After that, all you do is use the module, possibly listing those names that you want to import into your namespace. Using modules extremely easy. Note that you can usually get documentation on a module with the perldoc command.

Exmample:

use lib '.'; # If module lives in current directory
use Date::Calc ('check_date'); # load module, import symbol
 
 

Perl II Previous: 3. References Next: 5. Classes


1999-3-3  BobG
UIC Home Page Search UIC Pages Contact UIC