Advanced Perl Programming

Advanced Perl ProgrammingSearch this book
Previous: B.3 ClosuresAppendix B
Syntax Summary
Next: B.5 Objects
 

B.4 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    


Previous: B.3 ClosuresAdvanced Perl ProgrammingNext: B.5 Objects
B.3 ClosuresBook IndexB.5 Objects

Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.