1PERLMOD(1) Perl Programmers Reference Guide PERLMOD(1)
2
3
4
6 perlmod - Perl modules (packages and symbol tables)
7
9 Packages
10
11 Perl provides a mechanism for alternative namespaces to protect pack‐
12 ages from stomping on each other's variables. In fact, there's really
13 no such thing as a global variable in Perl. The package statement
14 declares the compilation unit as being in the given namespace. The
15 scope of the package declaration is from the declaration itself through
16 the end of the enclosing block, "eval", or file, whichever comes first
17 (the same scope as the my() and local() operators). Unqualified
18 dynamic identifiers will be in this namespace, except for those few
19 identifiers that if unqualified, default to the main package instead of
20 the current one as described below. A package statement affects only
21 dynamic variables--including those you've used local() on--but not lex‐
22 ical variables created with my(). Typically it would be the first dec‐
23 laration in a file included by the "do", "require", or "use" operators.
24 You can switch into a package in more than one place; it merely influ‐
25 ences which symbol table is used by the compiler for the rest of that
26 block. You can refer to variables and filehandles in other packages by
27 prefixing the identifier with the package name and a double colon:
28 $Package::Variable. If the package name is null, the "main" package is
29 assumed. That is, $::sail is equivalent to $main::sail.
30
31 The old package delimiter was a single quote, but double colon is now
32 the preferred delimiter, in part because it's more readable to humans,
33 and in part because it's more readable to emacs macros. It also makes
34 C++ programmers feel like they know what's going on--as opposed to
35 using the single quote as separator, which was there to make Ada pro‐
36 grammers feel like they knew what was going on. Because the old-fash‐
37 ioned syntax is still supported for backwards compatibility, if you try
38 to use a string like "This is $owner's house", you'll be accessing
39 $owner::s; that is, the $s variable in package "owner", which is proba‐
40 bly not what you meant. Use braces to disambiguate, as in "This is
41 ${owner}'s house".
42
43 Packages may themselves contain package separators, as in
44 $OUTER::INNER::var. This implies nothing about the order of name
45 lookups, however. There are no relative packages: all symbols are
46 either local to the current package, or must be fully qualified from
47 the outer package name down. For instance, there is nowhere within
48 package "OUTER" that $INNER::var refers to $OUTER::INNER::var. "INNER"
49 refers to a totally separate global package.
50
51 Only identifiers starting with letters (or underscore) are stored in a
52 package's symbol table. All other symbols are kept in package "main",
53 including all punctuation variables, like $_. In addition, when
54 unqualified, the identifiers STDIN, STDOUT, STDERR, ARGV, ARGVOUT, ENV,
55 INC, and SIG are forced to be in package "main", even when used for
56 other purposes than their built-in ones. If you have a package called
57 "m", "s", or "y", then you can't use the qualified form of an identi‐
58 fier because it would be instead interpreted as a pattern match, a sub‐
59 stitution, or a transliteration.
60
61 Variables beginning with underscore used to be forced into package
62 main, but we decided it was more useful for package writers to be able
63 to use leading underscore to indicate private variables and method
64 names. However, variables and functions named with a single "_", such
65 as $_ and "sub _", are still forced into the package "main". See also
66 "Technical Note on the Syntax of Variable Names" in perlvar.
67
68 "eval"ed strings are compiled in the package in which the eval() was
69 compiled. (Assignments to $SIG{}, however, assume the signal handler
70 specified is in the "main" package. Qualify the signal handler name if
71 you wish to have a signal handler in a package.) For an example, exam‐
72 ine perldb.pl in the Perl library. It initially switches to the "DB"
73 package so that the debugger doesn't interfere with variables in the
74 program you are trying to debug. At various points, however, it tempo‐
75 rarily switches back to the "main" package to evaluate various expres‐
76 sions in the context of the "main" package (or wherever you came from).
77 See perldebug.
78
79 The special symbol "__PACKAGE__" contains the current package, but can‐
80 not (easily) be used to construct variable names.
81
82 See perlsub for other scoping issues related to my() and local(), and
83 perlref regarding closures.
84
85 Symbol Tables
86
87 The symbol table for a package happens to be stored in the hash of that
88 name with two colons appended. The main symbol table's name is thus
89 %main::, or %:: for short. Likewise the symbol table for the nested
90 package mentioned earlier is named %OUTER::INNER::.
91
92 The value in each entry of the hash is what you are referring to when
93 you use the *name typeglob notation. In fact, the following have the
94 same effect, though the first is more efficient because it does the
95 symbol table lookups at compile time:
96
97 local *main::foo = *main::bar;
98 local $main::{foo} = $main::{bar};
99
100 (Be sure to note the vast difference between the second line above and
101 "local $main::foo = $main::bar". The former is accessing the hash
102 %main::, which is the symbol table of package "main". The latter is
103 simply assigning scalar $bar in package "main" to scalar $foo of the
104 same package.)
105
106 You can use this to print out all the variables in a package, for
107 instance. The standard but antiquated dumpvar.pl library and the CPAN
108 module Devel::Symdump make use of this.
109
110 Assignment to a typeglob performs an aliasing operation, i.e.,
111
112 *dick = *richard;
113
114 causes variables, subroutines, formats, and file and directory handles
115 accessible via the identifier "richard" also to be accessible via the
116 identifier "dick". If you want to alias only a particular variable or
117 subroutine, assign a reference instead:
118
119 *dick = \$richard;
120
121 Which makes $richard and $dick the same variable, but leaves @richard
122 and @dick as separate arrays. Tricky, eh?
123
124 There is one subtle difference between the following statements:
125
126 *foo = *bar;
127 *foo = \$bar;
128
129 "*foo = *bar" makes the typeglobs themselves synonymous while "*foo =
130 \$bar" makes the SCALAR portions of two distinct typeglobs refer to the
131 same scalar value. This means that the following code:
132
133 $bar = 1;
134 *foo = \$bar; # Make $foo an alias for $bar
135
136 {
137 local $bar = 2; # Restrict changes to block
138 print $foo; # Prints '1'!
139 }
140
141 Would print '1', because $foo holds a reference to the original $bar --
142 the one that was stuffed away by "local()" and which will be restored
143 when the block ends. Because variables are accessed through the type‐
144 glob, you can use "*foo = *bar" to create an alias which can be local‐
145 ized. (But be aware that this means you can't have a separate @foo and
146 @bar, etc.)
147
148 What makes all of this important is that the Exporter module uses glob
149 aliasing as the import/export mechanism. Whether or not you can prop‐
150 erly localize a variable that has been exported from a module depends
151 on how it was exported:
152
153 @EXPORT = qw($FOO); # Usual form, can't be localized
154 @EXPORT = qw(*FOO); # Can be localized
155
156 You can work around the first case by using the fully qualified name
157 ($Package::FOO) where you need a local value, or by overriding it by
158 saying "*FOO = *Package::FOO" in your script.
159
160 The "*x = \$y" mechanism may be used to pass and return cheap refer‐
161 ences into or from subroutines if you don't want to copy the whole
162 thing. It only works when assigning to dynamic variables, not lexi‐
163 cals.
164
165 %some_hash = (); # can't be my()
166 *some_hash = fn( \%another_hash );
167 sub fn {
168 local *hashsym = shift;
169 # now use %hashsym normally, and you
170 # will affect the caller's %another_hash
171 my %nhash = (); # do what you want
172 return \%nhash;
173 }
174
175 On return, the reference will overwrite the hash slot in the symbol ta‐
176 ble specified by the *some_hash typeglob. This is a somewhat tricky
177 way of passing around references cheaply when you don't want to have to
178 remember to dereference variables explicitly.
179
180 Another use of symbol tables is for making "constant" scalars.
181
182 *PI = \3.14159265358979;
183
184 Now you cannot alter $PI, which is probably a good thing all in all.
185 This isn't the same as a constant subroutine, which is subject to opti‐
186 mization at compile-time. A constant subroutine is one prototyped to
187 take no arguments and to return a constant expression. See perlsub for
188 details on these. The "use constant" pragma is a convenient shorthand
189 for these.
190
191 You can say *foo{PACKAGE} and *foo{NAME} to find out what name and
192 package the *foo symbol table entry comes from. This may be useful in
193 a subroutine that gets passed typeglobs as arguments:
194
195 sub identify_typeglob {
196 my $glob = shift;
197 print 'You gave me ', *{$glob}{PACKAGE}, '::', *{$glob}{NAME}, "\n";
198 }
199 identify_typeglob *foo;
200 identify_typeglob *bar::baz;
201
202 This prints
203
204 You gave me main::foo
205 You gave me bar::baz
206
207 The *foo{THING} notation can also be used to obtain references to the
208 individual elements of *foo. See perlref.
209
210 Subroutine definitions (and declarations, for that matter) need not
211 necessarily be situated in the package whose symbol table they occupy.
212 You can define a subroutine outside its package by explicitly qualify‐
213 ing the name of the subroutine:
214
215 package main;
216 sub Some_package::foo { ... } # &foo defined in Some_package
217
218 This is just a shorthand for a typeglob assignment at compile time:
219
220 BEGIN { *Some_package::foo = sub { ... } }
221
222 and is not the same as writing:
223
224 {
225 package Some_package;
226 sub foo { ... }
227 }
228
229 In the first two versions, the body of the subroutine is lexically in
230 the main package, not in Some_package. So something like this:
231
232 package main;
233
234 $Some_package::name = "fred";
235 $main::name = "barney";
236
237 sub Some_package::foo {
238 print "in ", __PACKAGE__, ": \$name is '$name'\n";
239 }
240
241 Some_package::foo();
242
243 prints:
244
245 in main: $name is 'barney'
246
247 rather than:
248
249 in Some_package: $name is 'fred'
250
251 This also has implications for the use of the SUPER:: qualifier (see
252 perlobj).
253
254 BEGIN, CHECK, INIT and END
255
256 Four specially named code blocks are executed at the beginning and at
257 the end of a running Perl program. These are the "BEGIN", "CHECK",
258 "INIT", and "END" blocks.
259
260 These code blocks can be prefixed with "sub" to give the appearance of
261 a subroutine (although this is not considered good style). One should
262 note that these code blocks don't really exist as named subroutines
263 (despite their appearance). The thing that gives this away is the fact
264 that you can have more than one of these code blocks in a program, and
265 they will get all executed at the appropriate moment. So you can't
266 execute any of these code blocks by name.
267
268 A "BEGIN" code block is executed as soon as possible, that is, the
269 moment it is completely defined, even before the rest of the containing
270 file (or string) is parsed. You may have multiple "BEGIN" blocks
271 within a file (or eval'ed string) -- they will execute in order of def‐
272 inition. Because a "BEGIN" code block executes immediately, it can
273 pull in definitions of subroutines and such from other files in time to
274 be visible to the rest of the compile and run time. Once a "BEGIN" has
275 run, it is immediately undefined and any code it used is returned to
276 Perl's memory pool.
277
278 It should be noted that "BEGIN" code blocks are executed inside string
279 "eval()"'s. The "CHECK" and "INIT" code blocks are not executed inside
280 a string eval, which e.g. can be a problem in a mod_perl environment.
281
282 An "END" code block is executed as late as possible, that is, after
283 perl has finished running the program and just before the interpreter
284 is being exited, even if it is exiting as a result of a die() function.
285 (But not if it's morphing into another program via "exec", or being
286 blown out of the water by a signal--you have to trap that yourself (if
287 you can).) You may have multiple "END" blocks within a file--they will
288 execute in reverse order of definition; that is: last in, first out
289 (LIFO). "END" blocks are not executed when you run perl with the "-c"
290 switch, or if compilation fails.
291
292 Note that "END" code blocks are not executed at the end of a string
293 "eval()": if any "END" code blocks are created in a string "eval()",
294 they will be executed just as any other "END" code block of that pack‐
295 age in LIFO order just before the interpreter is being exited.
296
297 Inside an "END" code block, $? contains the value that the program is
298 going to pass to "exit()". You can modify $? to change the exit value
299 of the program. Beware of changing $? by accident (e.g. by running
300 something via "system").
301
302 "CHECK" and "INIT" code blocks are useful to catch the transition
303 between the compilation phase and the execution phase of the main pro‐
304 gram.
305
306 "CHECK" code blocks are run just after the initial Perl compile phase
307 ends and before the run time begins, in LIFO order. "CHECK" code
308 blocks are used in the Perl compiler suite to save the compiled state
309 of the program.
310
311 "INIT" blocks are run just before the Perl runtime begins execution, in
312 "first in, first out" (FIFO) order. For example, the code generators
313 documented in perlcc make use of "INIT" blocks to initialize and
314 resolve pointers to XSUBs.
315
316 When you use the -n and -p switches to Perl, "BEGIN" and "END" work
317 just as they do in awk, as a degenerate case. Both "BEGIN" and "CHECK"
318 blocks are run when you use the -c switch for a compile-only syntax
319 check, although your main code is not.
320
321 The begincheck program makes it all clear, eventually:
322
323 #!/usr/bin/perl
324
325 # begincheck
326
327 print " 8. Ordinary code runs at runtime.\n";
328
329 END { print "14. So this is the end of the tale.\n" }
330 INIT { print " 5. INIT blocks run FIFO just before runtime.\n" }
331 CHECK { print " 4. So this is the fourth line.\n" }
332
333 print " 9. It runs in order, of course.\n";
334
335 BEGIN { print " 1. BEGIN blocks run FIFO during compilation.\n" }
336 END { print "13. Read perlmod for the rest of the story.\n" }
337 CHECK { print " 3. CHECK blocks run LIFO at compilation's end.\n" }
338 INIT { print " 6. Run this again, using Perl's -c switch.\n" }
339
340 print "10. This is anti-obfuscated code.\n";
341
342 END { print "12. END blocks run LIFO at quitting time.\n" }
343 BEGIN { print " 2. So this line comes out second.\n" }
344 INIT { print " 7. You'll see the difference right away.\n" }
345
346 print "11. It merely _looks_ like it should be confusing.\n";
347
348 __END__
349
350 Perl Classes
351
352 There is no special class syntax in Perl, but a package may act as a
353 class if it provides subroutines to act as methods. Such a package may
354 also derive some of its methods from another class (package) by listing
355 the other package name(s) in its global @ISA array (which must be a
356 package global, not a lexical).
357
358 For more on this, see perltoot and perlobj.
359
360 Perl Modules
361
362 A module is just a set of related functions in a library file, i.e., a
363 Perl package with the same name as the file. It is specifically
364 designed to be reusable by other modules or programs. It may do this
365 by providing a mechanism for exporting some of its symbols into the
366 symbol table of any package using it, or it may function as a class
367 definition and make its semantics available implicitly through method
368 calls on the class and its objects, without explicitly exporting any‐
369 thing. Or it can do a little of both.
370
371 For example, to start a traditional, non-OO module called Some::Module,
372 create a file called Some/Module.pm and start with this template:
373
374 package Some::Module; # assumes Some/Module.pm
375
376 use strict;
377 use warnings;
378
379 BEGIN {
380 use Exporter ();
381 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
382
383 # set the version for version checking
384 $VERSION = 1.00;
385 # if using RCS/CVS, this may be preferred
386 $VERSION = sprintf "%d.%03d", q$Revision: 1.1 $ =~ /(\d+)/g;
387
388 @ISA = qw(Exporter);
389 @EXPORT = qw(&func1 &func2 &func4);
390 %EXPORT_TAGS = ( ); # eg: TAG => [ qw!name1 name2! ],
391
392 # your exported package globals go here,
393 # as well as any optionally exported functions
394 @EXPORT_OK = qw($Var1 %Hashit &func3);
395 }
396 our @EXPORT_OK;
397
398 # exported package globals go here
399 our $Var1;
400 our %Hashit;
401
402 # non-exported package globals go here
403 our @more;
404 our $stuff;
405
406 # initialize package globals, first exported ones
407 $Var1 = '';
408 %Hashit = ();
409
410 # then the others (which are still accessible as $Some::Module::stuff)
411 $stuff = '';
412 @more = ();
413
414 # all file-scoped lexicals must be created before
415 # the functions below that use them.
416
417 # file-private lexicals go here
418 my $priv_var = '';
419 my %secret_hash = ();
420
421 # here's a file-private function as a closure,
422 # callable as &$priv_func; it cannot be prototyped.
423 my $priv_func = sub {
424 # stuff goes here.
425 };
426
427 # make all your functions, whether exported or not;
428 # remember to put something interesting in the {} stubs
429 sub func1 {} # no prototype
430 sub func2() {} # proto'd void
431 sub func3($$) {} # proto'd to 2 scalars
432
433 # this one isn't exported, but could be called!
434 sub func4(\%) {} # proto'd to 1 hash ref
435
436 END { } # module clean-up code here (global destructor)
437
438 ## YOUR CODE GOES HERE
439
440 1; # don't forget to return a true value from the file
441
442 Then go on to declare and use your variables in functions without any
443 qualifications. See Exporter and the perlmodlib for details on mechan‐
444 ics and style issues in module creation.
445
446 Perl modules are included into your program by saying
447
448 use Module;
449
450 or
451
452 use Module LIST;
453
454 This is exactly equivalent to
455
456 BEGIN { require Module; import Module; }
457
458 or
459
460 BEGIN { require Module; import Module LIST; }
461
462 As a special case
463
464 use Module ();
465
466 is exactly equivalent to
467
468 BEGIN { require Module; }
469
470 All Perl module files have the extension .pm. The "use" operator
471 assumes this so you don't have to spell out "Module.pm" in quotes.
472 This also helps to differentiate new modules from old .pl and .ph
473 files. Module names are also capitalized unless they're functioning as
474 pragmas; pragmas are in effect compiler directives, and are sometimes
475 called "pragmatic modules" (or even "pragmata" if you're a classicist).
476
477 The two statements:
478
479 require SomeModule;
480 require "SomeModule.pm";
481
482 differ from each other in two ways. In the first case, any double
483 colons in the module name, such as "Some::Module", are translated into
484 your system's directory separator, usually "/". The second case does
485 not, and would have to be specified literally. The other difference is
486 that seeing the first "require" clues in the compiler that uses of
487 indirect object notation involving "SomeModule", as in "$ob = purge
488 SomeModule", are method calls, not function calls. (Yes, this really
489 can make a difference.)
490
491 Because the "use" statement implies a "BEGIN" block, the importing of
492 semantics happens as soon as the "use" statement is compiled, before
493 the rest of the file is compiled. This is how it is able to function
494 as a pragma mechanism, and also how modules are able to declare subrou‐
495 tines that are then visible as list or unary operators for the rest of
496 the current file. This will not work if you use "require" instead of
497 "use". With "require" you can get into this problem:
498
499 require Cwd; # make Cwd:: accessible
500 $here = Cwd::getcwd();
501
502 use Cwd; # import names from Cwd::
503 $here = getcwd();
504
505 require Cwd; # make Cwd:: accessible
506 $here = getcwd(); # oops! no main::getcwd()
507
508 In general, "use Module ()" is recommended over "require Module",
509 because it determines module availability at compile time, not in the
510 middle of your program's execution. An exception would be if two mod‐
511 ules each tried to "use" each other, and each also called a function
512 from that other module. In that case, it's easy to use "require"
513 instead.
514
515 Perl packages may be nested inside other package names, so we can have
516 package names containing "::". But if we used that package name
517 directly as a filename it would make for unwieldy or impossible file‐
518 names on some systems. Therefore, if a module's name is, say,
519 "Text::Soundex", then its definition is actually found in the library
520 file Text/Soundex.pm.
521
522 Perl modules always have a .pm file, but there may also be dynamically
523 linked executables (often ending in .so) or autoloaded subroutine defi‐
524 nitions (often ending in .al) associated with the module. If so, these
525 will be entirely transparent to the user of the module. It is the
526 responsibility of the .pm file to load (or arrange to autoload) any
527 additional functionality. For example, although the POSIX module hap‐
528 pens to do both dynamic loading and autoloading, the user can say just
529 "use POSIX" to get it all.
530
531 Making your module threadsafe
532
533 Since 5.6.0, Perl has had support for a new type of threads called
534 interpreter threads (ithreads). These threads can be used explicitly
535 and implicitly.
536
537 Ithreads work by cloning the data tree so that no data is shared
538 between different threads. These threads can be used by using the
539 "threads" module or by doing fork() on win32 (fake fork() support).
540 When a thread is cloned all Perl data is cloned, however non-Perl data
541 cannot be cloned automatically. Perl after 5.7.2 has support for the
542 "CLONE" special subroutine. In "CLONE" you can do whatever you need to
543 do, like for example handle the cloning of non-Perl data, if necessary.
544 "CLONE" will be called once as a class method for every package that
545 has it defined (or inherits it). It will be called in the context of
546 the new thread, so all modifications are made in the new area. Cur‐
547 rently CLONE is called with no parameters other than the invocant pack‐
548 age name, but code should not assume that this will remain unchanged,
549 as it is likely that in future extra parameters will be passed in to
550 give more information about the state of cloning.
551
552 If you want to CLONE all objects you will need to keep track of them
553 per package. This is simply done using a hash and
554 Scalar::Util::weaken().
555
556 Perl after 5.8.7 has support for the "CLONE_SKIP" special subroutine.
557 Like "CLONE", "CLONE_SKIP" is called once per package; however, it is
558 called just before cloning starts, and in the context of the parent
559 thread. If it returns a true value, then no objects of that class will
560 be cloned; or rather, they will be copied as unblessed, undef values.
561 This provides a simple mechanism for making a module threadsafe; just
562 add "sub CLONE_SKIP { 1 }" at the top of the class, and "DESTROY()"
563 will be now only be called once per object. Of course, if the child
564 thread needs to make use of the objects, then a more sophisticated
565 approach is needed.
566
567 Like "CLONE", "CLONE_SKIP" is currently called with no parameters other
568 than the invocant package name, although that may change. Similarly, to
569 allow for future expansion, the return value should be a single 0 or 1
570 value.
571
573 See perlmodlib for general style issues related to building Perl mod‐
574 ules and classes, as well as descriptions of the standard library and
575 CPAN, Exporter for how Perl's standard import/export mechanism works,
576 perltoot and perltooc for an in-depth tutorial on creating classes,
577 perlobj for a hard-core reference document on objects, perlsub for an
578 explanation of functions and scoping, and perlxstut and perlguts for
579 more information on writing extension modules.
580
581
582
583perl v5.8.8 2006-01-07 PERLMOD(1)