Modules

  1. The package keyword starts a new namespace (which lasts until another package declaration or until end of block). All user-defined global identifiers (variables, subroutines, filehandles) belong to this package. Lexical variables do not belong to any package.

    package Employee; # Put in file Employee.pm
    @employees = ("John", "Fred", "Mary", "Sue");
    sub list_employee { print @employees; }
    1;                # Last executing statement in file must be 
                      # non-zero, to indicate successful loading
  2. To load module Employee:

    use Employee;
    #or 
    require Employee;

    Specify the load path with the -I command-line option, PERL5LIB environment variable, or @INC.

  3. Access foreign package’s variables and subroutines with fully qualified names:

    print @Employee::employees;    
    Employee::print();

    Privacy is not enforced.

  4. If a subroutine is not found in that package, a default subroutine AUTOLOAD() is called, if present. $AUTOLOAD is set to the fully qualified name of the missing subroutine.

  5. To inherit module C from modules A and B, prime C’s @ISA array with the names of its superclass modules:

    package A;
    sub foo{ print "A::foo called \n";}
    package C;
    @ISA = ("A", "B");
    C->foo();               # Calls A::foo, because B does not    

Get Advanced Perl Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.