Packages, Modules

Modules are included with use, a compiler directive. The extension .pm stands for perl module.

The package command switches between the packages (symbol tables).

Default package: $:: or $main::. The main symbol table is called %main::.

Packages may be nested: $OUTER::INNER:var.

Importing symbols:

#!/usr/bin/perl

sub sub1{ print "this is main::sub1 \n"; }
sub sub2{ print "this is main::sub2 \n"; }

use Tmodule qw( sub1 ); 

sub1(); 
sub2();

The module file contains:

#!/usr/bin/perl

package Tmodule;
require Exporter; 
@ISA = qw( Exporter); 
@EXPORT = qw( sub1 sub2); 
@EXPORT_OK = qw( $tvar ); 

sub sub1{ print "this is Tmodule::sub1 \n"; }
sub sub2{ print "this is Tmodule::sub2 \n"; }
$tvar = "12";
return 1;

The following output is generated:

this is Tmodule::sub1
this is main::sub2

Note that Tmodule::sub2 is exported but not mentioned in the use command. That's why the corresponding routine from main is executed.

require is executed at run-time. Routines from the required package have to be fully qualified, e.g.: Tmodule::sub1().

The function AUTOLOAD is called for all unresolved references:

sub AUTOLOAD { 
  my $program = $AUTOLOAD;
  $program =~ s/.*:://;
  system( $program, @_);
}
date();
who( 'am', 'i');
ls( '-1');



Subsections