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