Penguin
Annotated edit history of perlmod(1) version 2, including all changes. View license author blame.
Rev Author # Line
1 perry 1 PERLMOD
2 !!!PERLMOD
3 NAME
4 DESCRIPTION
5 SEE ALSO
6 ----
7 !!NAME
8
9
10 perlmod - Perl modules (packages and symbol tables)
11 !!DESCRIPTION
12
13
14 __Packages__
15
16
17 Perl provides a mechanism for alternative namespaces to
18 protect packages from stomping on each other's variables. In
19 fact, there's really no such thing as a global variable in
20 Perl. The package statement declares the compilation unit as
21 being in the given namespace. The scope of the package
22 declaration is from the declaration itself through the end
23 of the enclosing block, eval, or file, whichever
24 comes first (the same scope as the ''my()'' and
25 ''local()'' operators). Unqualified dynamic identifiers
26 will be in this namespace, except for those few identifiers
27 that if unqualified, default to the main package instead of
28 the current one as described below. A package statement
29 affects only dynamic variables--including those you've used
30 ''local()'' on--but ''not'' lexical variables created
31 with ''my()''. Typically it would be the first
32 declaration in a file included by the do,
33 require, or use operators. You can switch
34 into a package in more than one place; it merely influences
35 which symbol table is used by the compiler for the rest of
36 that block. You can refer to variables and filehandles in
37 other packages by prefixing the identifier with the package
38 name and a double colon: $Package::Variable. If the
39 package name is null, the main package is assumed.
40 That is, $::sail is equivalent to
41 $main::sail.
42
43
44 The old package delimiter was a single quote, but double
45 colon is now the preferred delimiter, in part because it's
46 more readable to humans, and in part because it's more
47 readable to __emacs__ macros. It also makes C
48 ++ programmers feel like they know what's
49 going on--as opposed to using the single quote as separator,
50 which was there to make Ada programmers feel like they knew
51 what's going on. Because the old-fashioned syntax is still
52 supported for backwards compatibility, if you try to use a
53 string like ,
54 you'll be accessing $owner::s; that is, the
55 $s variable in package owner, which is
56 probably not what you meant. Use braces to disambiguate, as
57 in
58 .
59
60
61 Packages may themselves contain package separators, as in
62 $OUTER::INNER::var. This implies nothing about the
63 order of name lookups, however. There are no relative
64 packages: all symbols are either local to the current
65 package, or must be fully qualified from the outer package
66 name down. For instance, there is nowhere within package
67 OUTER that $INNER::var refers to
68 $OUTER::INNER::var. It would treat package
69 INNER as a totally separate global
70 package.
71
72
73 Only identifiers starting with letters (or underscore) are
74 stored in a package's symbol table. All other symbols are
75 kept in package main, including all punctuation
76 variables, like $_. In addition, when unqualified,
77 the identifiers STDIN , STDOUT
78 , STDERR , ARGV ,
79 ARGVOUT , ENV ,
80 INC , and SIG are forced to be
81 in package main, even when used for other purposes
82 than their built-in one. If you have a package called
83 m, s, or y, then you can't use
84 the qualified form of an identifier because it would be
85 instead interpreted as a pattern match, a substitution, or a
86 transliteration.
87
88
89 Variables beginning with underscore used to be forced into
90 package main, but we decided it was more useful for package
91 writers to be able to use leading underscore to indicate
92 private variables and method names. $_ is still
93 global though. See also ``Technical Note on the Syntax of
94 Variable Names'' in perlvar.
95
96
97 evaled strings are compiled in the package in which
98 the ''eval()'' was compiled. (Assignments to
99 $SIG{}, however, assume the signal handler
100 specified is in the main package. Qualify the
101 signal handler name if you wish to have a signal handler in
102 a package.) For an example, examine ''perldb.pl'' in the
103 Perl library. It initially switches to the DB
104 package so that the debugger doesn't interfere with
105 variables in the program you are trying to debug. At various
106 points, however, it temporarily switches back to the
107 main package to evaluate various expressions in the
108 context of the main package (or wherever you came
109 from). See perldebug.
110
111
112 The special symbol __PACKAGE__ contains the current
113 package, but cannot (easily) be used to construct
114 variables.
115
116
117 See perlsub for other scoping issues related to ''my()''
118 and ''local()'', and perlref regarding
119 closures.
120
121
122 __Symbol Tables__
123
124
125 The symbol table for a package happens to be stored in the
126 hash of that name with two colons appended. The main symbol
127 table's name is thus %main::, or %:: for
128 short. Likewise the symbol table for the nested package
129 mentioned earlier is named
130 %OUTER::INNER::.
131
132
133 The value in each entry of the hash is what you are
134 referring to when you use the *name typeglob
135 notation. In fact, the following have the same effect,
136 though the first is more efficient because it does the
137 symbol table lookups at compile time:
138
139
140 local *main::foo = *main::bar;
141 local $main::{foo} = $main::{bar};
142 (Be sure to note the __vast__ difference between the second line above and local $main::foo = $main::bar. The former is accessing the hash %main::, which is the symbol table of package main. The latter is simply assigning scalar $bar in package main to scalar $foo of the same package.)
143
144
145 You can use this to print out all the variables in a
146 package, for instance. The standard but antiquated
147 ''dumpvar.pl'' library and the CPAN module
148 Devel::Symdump make use of this.
149
150
151 Assignment to a typeglob performs an aliasing operation,
152 i.e.,
153
154
155 *dick = *richard;
156 causes variables, subroutines, formats, and file and directory handles accessible via the identifier richard also to be accessible via the identifier dick. If you want to alias only a particular variable or subroutine, assign a reference instead:
157
158
159 *dick = $richard;
160 Which makes $richard and $dick the same variable, but leaves @richard and @dick as separate arrays. Tricky, eh?
161
162
163 This mechanism may be used to pass and return cheap
164 references into or from subroutines if you don't want to
165 copy the whole thing. It only works when assigning to
166 dynamic variables, not lexicals.
167
168
169 %some_hash = (); # can't be my()
170 *some_hash = fn( %another_hash );
171 sub fn {
172 local *hashsym = shift;
173 # now use %hashsym normally, and you
174 # will affect the caller's %another_hash
175 my %nhash = (); # do what you want
176 return %nhash;
177 }
178 On return, the reference will overwrite the hash slot in the symbol table specified by the *some_hash typeglob. This is a somewhat tricky way of passing around references cheaply when you don't want to have to remember to dereference variables explicitly.
179
180
181 Another use of symbol tables is for making ``constant''
182 scalars.
183
184
185 *PI = 3.14159265358979;
186 Now you cannot alter $PI, which is probably a good thing all in all. This isn't the same as a constant subroutine, which is subject to optimization at compile-time. A constant subroutine is one prototyped to take no arguments and to return a constant expression. See perlsub for details on these. The use constant pragma is a convenient shorthand for these.
187
188
189 You can say *foo{PACKAGE} and *foo{NAME}
190 to find out what name and package the *foo symbol table
191 entry comes from. This may be useful in a subroutine that
192 gets passed typeglobs as arguments:
193
194
195 sub identify_typeglob {
196 my $glob = shift;
197 print 'You gave me ', *{$glob}{PACKAGE}, '::', *{$glob}{NAME},
198 This prints
199
200
201 You gave me main::foo
202 You gave me bar::baz
203 The *foo{THING} notation can also be used to obtain references to the individual elements of *foo. See perlref.
204
205
206 Subroutine definitions (and declarations, for that matter)
207 need not necessarily be situated in the package whose symbol
208 table they occupy. You can define a subroutine outside its
209 package by explicitly qualifying the name of the
210 subroutine:
211
212
213 package main;
214 sub Some_package::foo { ... } #
215 This is just a shorthand for a typeglob assignment at compile time:
216
217
218 BEGIN { *Some_package::foo = sub { ... } }
219 and is ''not'' the same as writing:
220
221
222 {
223 package Some_package;
224 sub foo { ... }
225 }
226 In the first two versions, the body of the subroutine is lexically in the main package, ''not'' in Some_package. So something like this:
227
228
229 package main;
230 $Some_package::name =
231 sub Some_package::foo {
232 print
233 Some_package::foo();
234 prints:
235
236
237 in main: $name is 'barney'
238 rather than:
239
240
241 in Some_package: $name is 'fred'
242 This also has implications for the use of the SUPER:: qualifier (see perlobj).
243
244
245 __Package Constructors and Destructors__
246
247
248 Four special subroutines act as package constructors and
249 destructors. These are the BEGIN, CHECK,
250 INIT, and END routines. The sub
251 is optional for these routines.
252
253
254 A BEGIN subroutine is executed as soon as possible,
255 that is, the moment it is completely defined, even before
256 the rest of the containing file is parsed. You may have
257 multiple BEGIN blocks within a file--they will
258 execute in order of definition. Because a BEGIN
259 block executes immediately, it can pull in definitions of
260 subroutines and such from other files in time to be visible
261 to the rest of the file. Once a BEGIN has run, it
262 is immediately undefined and any code it used is returned to
263 Perl's memory pool. This means you can't ever explicitly
264 call a BEGIN.
265
266
267 An END subroutine is executed as late as possible,
268 that is, after perl has finished running the program and
269 just before the interpreter is being exited, even if it is
270 exiting as a result of a ''die()'' function. (But not if
271 it's polymorphing into another program via exec, or
272 being blown out of the water by a signal--you have to trap
273 that yourself (if you can).) You may have multiple
274 END blocks within a file--they will execute in
275 reverse order of definition; that is: last in, first out (
276 LIFO ). END blocks are not executed
277 when you run perl with the -c switch, or if
278 compilation fails.
279
280
281 Inside an END subroutine, $? contains the
282 value that the program is going to pass to exit().
283 You can modify $? to change the exit value of the
284 program. Beware of changing $? by accident (e.g. by
285 running something via system).
286
287
288 Similar to BEGIN blocks, INIT blocks are
289 run just before the Perl runtime begins execution, in
290 ``first in, first out'' ( FIFO ) order. For
291 example, the code generators documented in perlcc make use
292 of INIT blocks to initialize and resolve pointers
293 to XSUBs.
294
295
296 Similar to END blocks, CHECK blocks are
297 run just after the Perl compile phase ends and before the
298 run time begins, in LIFO order.
299 CHECK blocks are again useful in the Perl compiler
300 suite to save the compiled state of the
301 program.
302
303
304 When you use the __-n__ and __-p__ switches to Perl,
305 BEGIN and END work just as they do in
306 __awk__, as a degenerate case. Both BEGIN and
307 CHECK blocks are run when you use the __-c__
308 switch for a compile-only syntax check, although your main
309 code is not.
310
311
312 __Perl Classes__
313
314
315 There is no special class syntax in Perl, but a package may
316 act as a class if it provides subroutines to act as methods.
317 Such a package may also derive some of its methods from
318 another class (package) by listing the other package name(s)
319 in its global @ISA array (which must be a package
320 global, not a lexical).
321
322
323 For more on this, see perltoot and perlobj.
324
325
326 __Perl Modules__
327
328
329 A module is just a set of related functions in a library
330 file, i.e., a Perl package with the same name as the file.
331 It is specifically designed to be reusable by other modules
332 or programs. It may do this by providing a mechanism for
333 exporting some of its symbols into the symbol table of any
334 package using it. Or it may function as a class definition
335 and make its semantics available implicitly through method
336 calls on the class and its objects, without explicitly
337 exporting anything. Or it can do a little of
338 both.
339
340
341 For example, to start a traditional, non-OO module called
342 Some::Module, create a file called ''Some/Module.pm'' and
343 start with this template:
344
345
346 package Some::Module; # assumes Some/Module.pm
347 use strict;
348 use warnings;
349 BEGIN {
350 use Exporter ();
351 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
352 # set the version for version checking
353 $VERSION = 1.00;
354 # if using RCS/CVS, this may be preferred
355 $VERSION = do { my @r = (q$Revision: 2.21 $ =~ /d+/g); sprintf
356 @ISA = qw(Exporter);
357 @EXPORT = qw(
358 # your exported package globals go here,
359 # as well as any optionally exported functions
360 @EXPORT_OK = qw($Var1 %Hashit
361 # exported package globals go here
362 our $Var1;
363 our %Hashit;
364 # non-exported package globals go here
365 our @more;
366 our $stuff;
367 # initialize package globals, first exported ones
368 $Var1 = '';
369 %Hashit = ();
370 # then the others (which are still accessible as $Some::Module::stuff)
371 $stuff = '';
372 @more = ();
373 # all file-scoped lexicals must be created before
374 # the functions below that use them.
375 # file-private lexicals go here
376 my $priv_var = '';
377 my %secret_hash = ();
378 # here's a file-private function as a closure,
379 # callable as
380 # make all your functions, whether exported or not;
381 # remember to put something interesting in the {} stubs
382 sub func1 {} # no prototype
383 sub func2() {} # proto'd void
384 sub func3($$) {} # proto'd to 2 scalars
385 # this one isn't exported, but could be called!
386 sub func4(%) {} # proto'd to 1 hash ref
387 END { } # module clean-up code here (global destructor)
388 ## YOUR CODE GOES HERE
389 1; # don't forget to return a true value from the file
390 Then go on to declare and use your variables in functions without any qualifications. See Exporter and the perlmodlib for details on mechanics and style issues in module creation.
391
392
393 Perl modules are included into your program by
394 saying
395
396
397 use Module;
398 or
399
400
401 use Module LIST;
402 This is exactly equivalent to
403
404
405 BEGIN { require Module; import Module; }
406 or
407
408
409 BEGIN { require Module; import Module LIST; }
410 As a special case
411
412
413 use Module ();
414 is exactly equivalent to
415
416
417 BEGIN { require Module; }
418 All Perl module files have the extension ''.pm''. The use operator assumes this so you don't have to spell out Module.pm''''.pl'' and ''.ph'' files. Module names are also capitalized unless they're functioning as pragmas; pragmas are in effect compiler directives, and are sometimes called ``pragmatic modules'' (or even ``pragmata'' if you're a classicist).
419
420
421 The two statements:
422
423
2 perry 424 require !SomeModule;
1 perry 425 require
2 perry 426 differ from each other in two ways. In the first case, any double colons in the module name, such as Some::Module, are translated into your system's directory separator, usually ``/''. The second case does not, and would have to be specified literally. The other difference is that seeing the first require clues in the compiler that uses of indirect object notation involving ``!SomeModule'', as in $ob = purge !SomeModule, are method calls, not function calls. (Yes, this really can make a difference.)
1 perry 427
428
429 Because the use statement implies a BEGIN
430 block, the importing of semantics happens as soon as the
431 use statement is compiled, before the rest of the
432 file is compiled. This is how it is able to function as a
433 pragma mechanism, and also how modules are able to declare
434 subroutines that are then visible as list or unary operators
435 for the rest of the current file. This will not work if you
436 use require instead of use. With
437 require you can get into this problem:
438
439
440 require Cwd; # make Cwd:: accessible
441 $here = Cwd::getcwd();
442 use Cwd; # import names from Cwd::
443 $here = getcwd();
444 require Cwd; # make Cwd:: accessible
445 $here = getcwd(); # oops! no main::getcwd()
446 In general, use Module () is recommended over require Module, because it determines module availability at compile time, not in the middle of your program's execution. An exception would be if two modules each tried to use each other, and each also called a function from that other module. In that case, it's easy to use requires instead.
447
448
449 Perl packages may be nested inside other package names, so
450 we can have package names containing ::. But if we
451 used that package name directly as a filename it would make
452 for unwieldy or impossible filenames on some systems.
453 Therefore, if a module's name is, say,
454 Text::Soundex, then its definition is actually
455 found in the library file
456 ''Text/Soundex.pm''.
457
458
459 Perl modules always have a ''.pm'' file, but there may
460 also be dynamically linked executables (often ending in
461 ''.so'') or autoloaded subroutine definitions (often
462 ending in ''.al'') associated with the module. If so,
463 these will be entirely transparent to the user of the
464 module. It is the responsibility of the ''.pm'' file to
465 load (or arrange to autoload) any additional functionality.
466 For example, although the POSIX module
467 happens to do both dynamic loading and autoloading, the user
468 can say just use POSIX to get it all.
469 !!SEE ALSO
470
471
472 See perlmodlib for general style issues related to building
473 Perl modules and classes, as well as descriptions of the
474 standard library and CPAN , Exporter for how
475 Perl's standard import/export mechanism works, perltoot and
476 perltootc for an in-depth tutorial on creating classes,
477 perlobj for a hard-core reference document on objects,
478 perlsub for an explanation of functions and scoping, and
479 perlxstut and perlguts for more information on writing
480 extension modules.
481 ----
This page is a man page (or other imported legacy content). We are unable to automatically determine the license status of this page.