Perl Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 5.00

Exporting and Importing Package Identifiers

This section provides a tutorial example on how to access identifiers from another package as aliases, *identifier = *package::identifier.

Instead of asking all the calling packages to define aliases, Perl offers a solution to help package to export identifiers (symbols) automatically to the calling packages. Perl offers a helping package called Exporter, which can be used to help your package to define aliases into the calling packages.

To prepare a package to export identifiers (symbols), you need to add the following lines:

   package ModuleName;
   require Exporter;
   @ISA = qw(Exporter);
   @EXPORT = qw(...);       # symbols to export by default
   @EXPORT_OK = qw(...);    # symbols to export on request

To import identifiers (symbols) from an included package, you need to use the "use" statement in one of the following formats:

  use ModuleName;           # import default symbols into my package
  use ModuleName qw(...);   # import listed symbols into my package
  use ModuleName ();        # do not import any symbols

Let's see how I improved my old package to use Exporter. Here is the calendar package ready to export identifier:

#- CalendarExported.pm
#- Copyright (c) 1999 by Dr. Herong Yang, http://www.herongyang.com/
#
   package CalendarExported;
   require Exporter;
   @ISA = qw(Exporter);
   @EXPORT = qw($sec $min $hour $mday $mon $year $wday $yday);
   @EXPORT_OK = qw($swday $smon $smday $stime $syear &isLeapYear);
   sub BEGIN {
      $author = "Dr. Herong Yang";
      ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$x) = localtime();
      ($swday,$smon,$smday,$stime,$syear) = split(' ',localtime());
   }
   sub isLeapYear {
      local $day59 = time() - ($yday-59)*24*60*60;
      local ($0,$1,$2,$3,$m,$5,$6,$7,$8) = localtime($day59);
      $m = 0 unless $m==1;
      return $m;
   }
1;

Here is a program to show you how to import identifiers with the "use" statements:

#- CalendarImportTest.pl
#- Copyright (c) 1999 by Dr. Herong Yang, http://www.herongyang.com/
#
   use CalendarExported qw($smon $smday $stime $syear &isLeapYear);
   print("Date: $smon $smday $syear\n");
   print("Leap year? ",&isLeapYear(),"\n");
   exit;

Sections in This Chapter

Typeglob, Symbolic Table and Identifier Aliases

Accessing Identifiers from Other Packages as Aliases

Exporting and Importing Package Identifiers

Dr. Herong Yang, updated in 2008
Exporting and Importing Package Identifiers