3 perlmod - Perl modules (packages and symbol tables)
9 Perl provides a mechanism for alternative namespaces to protect packages
10 from stomping on each other's variables. In fact, there's really no such
11 thing as a global variable in Perl (although some identifiers default
12 to the main package instead of the current one). The package statement
13 declares the compilation unit as
14 being in the given namespace. The scope of the package declaration
15 is from the declaration itself through the end of the enclosing block,
16 C<eval>, C<sub>, or end of file, whichever comes first (the same scope
17 as the my() and local() operators). All further unqualified dynamic
18 identifiers will be in this namespace. A package statement only affects
19 dynamic variables--including those you've used local() on--but
20 I<not> lexical variables created with my(). Typically it would be
21 the first declaration in a file to be included by the C<require> or
22 C<use> operator. You can switch into a package in more than one place;
23 it merely influences which symbol table is used by the compiler for the
24 rest of that block. You can refer to variables and filehandles in other
25 packages by prefixing the identifier with the package name and a double
26 colon: C<$Package::Variable>. If the package name is null, the C<main>
27 package is assumed. That is, C<$::sail> is equivalent to C<$main::sail>.
29 (The old package delimiter was a single quote, but double colon
30 is now the preferred delimiter, in part because it's more readable
31 to humans, and in part because it's more readable to B<emacs> macros.
32 It also makes C++ programmers feel like they know what's going on.)
34 Packages may be nested inside other packages: C<$OUTER::INNER::var>. This
35 implies nothing about the order of name lookups, however. All symbols
36 are either local to the current package, or must be fully qualified
37 from the outer package name down. For instance, there is nowhere
38 within package C<OUTER> that C<$INNER::var> refers to C<$OUTER::INNER::var>.
39 It would treat package C<INNER> as a totally separate global package.
41 Only identifiers starting with letters (or underscore) are stored in a
42 package's symbol table. All other symbols are kept in package C<main>,
43 including all of the punctuation variables like $_. In addition, when
44 unqualified, the identifiers STDIN, STDOUT, STDERR, ARGV, ARGVOUT, ENV,
45 INC, and SIG are forced to be in package C<main>, even when used for other
46 purposes than their builtin one. Note also that, if you have a package
47 called C<m>, C<s>, or C<y>, then you can't use the qualified form of an
48 identifier because it will be interpreted instead as a pattern match,
49 a substitution, or a transliteration.
51 (Variables beginning with underscore used to be forced into package
52 main, but we decided it was more useful for package writers to be able
53 to use leading underscore to indicate private variables and method names.
54 $_ is still global though.)
56 Eval()ed strings are compiled in the package in which the eval() was
57 compiled. (Assignments to C<$SIG{}>, however, assume the signal
58 handler specified is in the C<main> package. Qualify the signal handler
59 name if you wish to have a signal handler in a package.) For an
60 example, examine F<perldb.pl> in the Perl library. It initially switches
61 to the C<DB> package so that the debugger doesn't interfere with variables
62 in the script you are trying to debug. At various points, however, it
63 temporarily switches back to the C<main> package to evaluate various
64 expressions in the context of the C<main> package (or wherever you came
65 from). See L<perldebug>.
67 The special symbol C<__PACKAGE__> contains the current package, but cannot
68 (easily) be used to construct variables.
70 See L<perlsub> for other scoping issues related to my() and local(),
71 and L<perlref> regarding closures.
75 The symbol table for a package happens to be stored in the hash of that
76 name with two colons appended. The main symbol table's name is thus
77 C<%main::>, or C<%::> for short. Likewise symbol table for the nested
78 package mentioned earlier is named C<%OUTER::INNER::>.
80 The value in each entry of the hash is what you are referring to when you
81 use the C<*name> typeglob notation. In fact, the following have the same
82 effect, though the first is more efficient because it does the symbol
83 table lookups at compile time:
85 local *main::foo = *main::bar;
86 local $main::{foo} = $main::{bar};
88 You can use this to print out all the variables in a package, for
89 instance. The standard F<dumpvar.pl> library and the CPAN module
90 Devel::Symdump make use of this.
92 Assignment to a typeglob performs an aliasing operation, i.e.,
96 causes variables, subroutines, formats, and file and directory handles
97 accessible via the identifier C<richard> also to be accessible via the
98 identifier C<dick>. If you want to alias only a particular variable or
99 subroutine, you can assign a reference instead:
103 Which makes $richard and $dick the same variable, but leaves
104 @richard and @dick as separate arrays. Tricky, eh?
106 This mechanism may be used to pass and return cheap references
107 into or from subroutines if you won't want to copy the whole
108 thing. It only works when assigning to dynamic variables, not
111 %some_hash = (); # can't be my()
112 *some_hash = fn( \%another_hash );
114 local *hashsym = shift;
115 # now use %hashsym normally, and you
116 # will affect the caller's %another_hash
117 my %nhash = (); # do what you want
121 On return, the reference will overwrite the hash slot in the
122 symbol table specified by the *some_hash typeglob. This
123 is a somewhat tricky way of passing around references cheaply
124 when you won't want to have to remember to dereference variables
127 Another use of symbol tables is for making "constant" scalars.
129 *PI = \3.14159265358979;
131 Now you cannot alter $PI, which is probably a good thing all in all.
132 This isn't the same as a constant subroutine, which is subject to
133 optimization at compile-time. This isn't. A constant subroutine is one
134 prototyped to take no arguments and to return a constant expression.
135 See L<perlsub> for details on these. The C<use constant> pragma is a
136 convenient shorthand for these.
138 You can say C<*foo{PACKAGE}> and C<*foo{NAME}> to find out what name and
139 package the *foo symbol table entry comes from. This may be useful
140 in a subroutine that gets passed typeglobs as arguments:
142 sub identify_typeglob {
144 print 'You gave me ', *{$glob}{PACKAGE}, '::', *{$glob}{NAME}, "\n";
146 identify_typeglob *foo;
147 identify_typeglob *bar::baz;
151 You gave me main::foo
154 The *foo{THING} notation can also be used to obtain references to the
155 individual elements of *foo, see L<perlref>.
157 =head2 Package Constructors and Destructors
159 There are two special subroutine definitions that function as package
160 constructors and destructors. These are the C<BEGIN> and C<END>
161 routines. The C<sub> is optional for these routines.
163 A C<BEGIN> subroutine is executed as soon as possible, that is, the moment
164 it is completely defined, even before the rest of the containing file
165 is parsed. You may have multiple C<BEGIN> blocks within a file--they
166 will execute in order of definition. Because a C<BEGIN> block executes
167 immediately, it can pull in definitions of subroutines and such from other
168 files in time to be visible to the rest of the file. Once a C<BEGIN>
169 has run, it is immediately undefined and any code it used is returned to
170 Perl's memory pool. This means you can't ever explicitly call a C<BEGIN>.
172 An C<END> subroutine is executed as late as possible, that is, when
173 the interpreter is being exited, even if it is exiting as a result of
174 a die() function. (But not if it's polymorphing into another program
175 via C<exec>, or being blown out of the water by a signal--you have to
176 trap that yourself (if you can).) You may have multiple C<END> blocks
177 within a file--they will execute in reverse order of definition; that is:
178 last in, first out (LIFO).
180 Inside an C<END> subroutine, C<$?> contains the value that the script is
181 going to pass to C<exit()>. You can modify C<$?> to change the exit
182 value of the script. Beware of changing C<$?> by accident (e.g. by
183 running something via C<system>).
185 Note that when you use the B<-n> and B<-p> switches to Perl, C<BEGIN> and
186 C<END> work just as they do in B<awk>, as a degenerate case. As currently
187 implemented (and subject to change, since its inconvenient at best),
188 both C<BEGIN> I<and> C<END> blocks are run when you use the B<-c> switch
189 for a compile-only syntax check, although your main code is not.
193 There is no special class syntax in Perl, but a package may function
194 as a class if it provides subroutines to act as methods. Such a
195 package may also derive some of its methods from another class (package)
196 by listing the other package name in its global @ISA array (which
197 must be a package global, not a lexical).
199 For more on this, see L<perltoot> and L<perlobj>.
203 A module is just a package that is defined in a library file of
204 the same name, and is designed to be reusable. It may do this by
205 providing a mechanism for exporting some of its symbols into the symbol
206 table of any package using it. Or it may function as a class
207 definition and make its semantics available implicitly through method
208 calls on the class and its objects, without explicit exportation of any
209 symbols. Or it can do a little of both.
211 For example, to start a normal module called Some::Module, create
212 a file called Some/Module.pm and start with this template:
214 package Some::Module; # assumes Some/Module.pm
220 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
222 # set the version for version checking
224 # if using RCS/CVS, this may be preferred
225 $VERSION = do { my @r = (q$Revision: 2.21 $ =~ /\d+/g); sprintf "%d."."%02d" x $#r, @r }; # must be all one line, for MakeMaker
228 @EXPORT = qw(&func1 &func2 &func4);
229 %EXPORT_TAGS = ( ); # eg: TAG => [ qw!name1 name2! ],
231 # your exported package globals go here,
232 # as well as any optionally exported functions
233 @EXPORT_OK = qw($Var1 %Hashit &func3);
237 # non-exported package globals go here
238 use vars qw(@more $stuff);
240 # initalize package globals, first exported ones
244 # then the others (which are still accessible as $Some::Module::stuff)
248 # all file-scoped lexicals must be created before
249 # the functions below that use them.
251 # file-private lexicals go here
253 my %secret_hash = ();
255 # here's a file-private function as a closure,
256 # callable as &$priv_func; it cannot be prototyped.
257 my $priv_func = sub {
261 # make all your functions, whether exported or not;
262 # remember to put something interesting in the {} stubs
263 sub func1 {} # no prototype
264 sub func2() {} # proto'd void
265 sub func3($$) {} # proto'd to 2 scalars
267 # this one isn't exported, but could be called!
268 sub func4(\%) {} # proto'd to 1 hash ref
270 END { } # module clean-up code here (global destructor)
272 Then go on to declare and use your variables in functions
273 without any qualifications.
274 See L<Exporter> and the L<perlmodlib> for details on
275 mechanics and style issues in module creation.
277 Perl modules are included into your program by saying
285 This is exactly equivalent to
287 BEGIN { require Module; import Module; }
291 BEGIN { require Module; import Module LIST; }
297 is exactly equivalent to
299 BEGIN { require Module; }
301 All Perl module files have the extension F<.pm>. C<use> assumes this so
302 that you don't have to spell out "F<Module.pm>" in quotes. This also
303 helps to differentiate new modules from old F<.pl> and F<.ph> files.
304 Module names are also capitalized unless they're functioning as pragmas,
305 "Pragmas" are in effect compiler directives, and are sometimes called
306 "pragmatic modules" (or even "pragmata" if you're a classicist).
311 require "SomeModule.pm";
313 differ from each other in two ways. In the first case, any double
314 colons in the module name, such as C<Some::Module>, are translated
315 into your system's directory separator, usually "/". The second
316 case does not, and would have to be specified literally. The other difference
317 is that seeing the first C<require> clues in the compiler that uses of
318 indirect object notation involving "SomeModule", as in C<$ob = purge SomeModule>,
319 are method calls, not function calls. (Yes, this really can make a difference.)
321 Because the C<use> statement implies a C<BEGIN> block, the importation
322 of semantics happens at the moment the C<use> statement is compiled,
323 before the rest of the file is compiled. This is how it is able
324 to function as a pragma mechanism, and also how modules are able to
325 declare subroutines that are then visible as list operators for
326 the rest of the current file. This will not work if you use C<require>
327 instead of C<use>. With require you can get into this problem:
329 require Cwd; # make Cwd:: accessible
330 $here = Cwd::getcwd();
332 use Cwd; # import names from Cwd::
335 require Cwd; # make Cwd:: accessible
336 $here = getcwd(); # oops! no main::getcwd()
338 In general, C<use Module ()> is recommended over C<require Module>,
339 because it determines module availability at compile time, not in the
340 middle of your program's execution. An exception would be if two modules
341 each tried to C<use> each other, and each also called a function from
342 that other module. In that case, it's easy to use C<require>s instead.
344 Perl packages may be nested inside other package names, so we can have
345 package names containing C<::>. But if we used that package name
346 directly as a filename it would makes for unwieldy or impossible
347 filenames on some systems. Therefore, if a module's name is, say,
348 C<Text::Soundex>, then its definition is actually found in the library
349 file F<Text/Soundex.pm>.
351 Perl modules always have a F<.pm> file, but there may also be dynamically
352 linked executables or autoloaded subroutine definitions associated with
353 the module. If so, these will be entirely transparent to the user of
354 the module. It is the responsibility of the F<.pm> file to load (or
355 arrange to autoload) any additional functionality. The POSIX module
356 happens to do both dynamic loading and autoloading, but the user can
357 say just C<use POSIX> to get it all.
359 For more information on writing extension modules, see L<perlxstut>
364 See L<perlmodlib> for general style issues related to building Perl
365 modules and classes as well as descriptions of the standard library and
366 CPAN, L<Exporter> for how Perl's standard import/export mechanism works,
367 L<perltoot> for an in-depth tutorial on creating classes, L<perlobj>
368 for a hard-core reference document on objects, and L<perlsub> for an
369 explanation of functions and scoping.