Debian Codegraph @

upstream/debian-unstable/man1/perlmod.1

raw
1 .\" -*- mode: troff; coding: utf-8 -*-
2 .\" Automatically generated by Pod::Man 5.0102 (Pod::Simple 3.45)
3 .\"
4 .\" Standard preamble:
5 .\" ========================================================================
6 .de Sp \" Vertical space (when we can't use .PP)
7 .if t .sp .5v
8 .if n .sp
9 ..
10 .de Vb \" Begin verbatim text
11 .ft CW
12 .nf
13 .ne \\$1
14 ..
15 .de Ve \" End verbatim text
16 .ft R
17 .fi
18 ..
19 .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>.
20 .ie n \{\
21 . ds C` ""
22 . ds C' ""
23 'br\}
24 .el\{\
25 . ds C`
26 . ds C'
27 'br\}
28 .\"
29 .\" Escape single quotes in literal strings from groff's Unicode transform.
30 .ie \n(.g .ds Aq \(aq
31 .el .ds Aq '
32 .\"
33 .\" If the F register is >0, we'll generate index entries on stderr for
34 .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
35 .\" entries marked with X<> in POD. Of course, you'll have to process the
36 .\" output yourself in some meaningful fashion.
37 .\"
38 .\" Avoid warning from groff about undefined register 'F'.
39 .de IX
40 ..
41 .nr rF 0
42 .if \n(.g .if rF .nr rF 1
43 .if (\n(rF:(\n(.g==0)) \{\
44 . if \nF \{\
45 . de IX
46 . tm Index:\\$1\t\\n%\t"\\$2"
47 ..
48 . if !\nF==2 \{\
49 . nr % 0
50 . nr F 2
51 . \}
52 . \}
53 .\}
54 .rr rF
55 .\" ========================================================================
56 .\"
57 .IX Title "PERLMOD 1"
58 .TH PERLMOD 1 2025-11-16 "perl v5.40.1" "Perl Programmers Reference Guide"
59 .\" For nroff, turn off justification. Always turn off hyphenation; it makes
60 .\" way too many mistakes in technical documents.
61 .if n .ad l
62 .nh
63 .SH NAME
64 perlmod \- Perl modules (packages and symbol tables)
65 .SH DESCRIPTION
66 .IX Header "DESCRIPTION"
67 .SS "Is this the document you were after?"
68 .IX Subsection "Is this the document you were after?"
69 There are other documents which might contain the information that you're
70 looking for:
71 .IP "This doc" 2
72 .IX Item "This doc"
73 Perl's packages, namespaces, and some info on classes.
74 .IP perlnewmod 2
75 .IX Item "perlnewmod"
76 Tutorial on making a new module.
77 .IP perlmodstyle 2
78 .IX Item "perlmodstyle"
79 Best practices for making a new module.
80 .SS Packages
81 .IX Xref "package namespace variable, global global variable global"
82 .IX Subsection "Packages"
83 Unlike Perl 4, in which all the variables were dynamic and shared one
84 global name space, causing maintainability problems, Perl 5 provides two
85 mechanisms for protecting code from having its variables stomped on by
86 other code: lexically scoped variables created with \f(CW\*(C`my\*(C'\fR or \f(CW\*(C`state\*(C'\fR and
87 namespaced global variables, which are exposed via the \f(CW\*(C`vars\*(C'\fR pragma,
88 or the \f(CW\*(C`our\*(C'\fR keyword. Any global variable is considered to
89 be part of a namespace and can be accessed via a "fully qualified form".
90 Conversely, any lexically scoped variable is considered to be part of
91 that lexical-scope, and does not have a "fully qualified form".
92 .PP
93 In perl namespaces are called "packages" and
94 the \f(CW\*(C`package\*(C'\fR declaration tells the compiler which
95 namespace to prefix to \f(CW\*(C`our\*(C'\fR variables and unqualified dynamic names.
96 This both protects
97 against accidental stomping and provides an interface for deliberately
98 clobbering global dynamic variables declared and used in other scopes or
99 packages, when that is what you want to do.
100 .PP
101 The scope of the \f(CW\*(C`package\*(C'\fR declaration is from the
102 declaration itself through the end of the enclosing block, \f(CW\*(C`eval\*(C'\fR,
103 or file, whichever comes first (the same scope as the \fBmy()\fR, \fBour()\fR, \fBstate()\fR, and
104 \&\fBlocal()\fR operators, and also the effect
105 of the experimental "reference aliasing," which may change), or until
106 the next \f(CW\*(C`package\*(C'\fR declaration. Unqualified dynamic identifiers will be in
107 this namespace, except for those few identifiers that, if unqualified,
108 default to the main package instead of the current one as described
109 below. A \f(CW\*(C`package\*(C'\fR statement affects only dynamic global
110 symbols, including subroutine names, and variables you've used \fBlocal()\fR
111 on, but \fInot\fR lexical variables created with \fBmy()\fR, \fBour()\fR or \fBstate()\fR.
112 .PP
113 Typically, a \f(CW\*(C`package\*(C'\fR statement is the first declaration in a file
114 included in a program by one of the \f(CW\*(C`do\*(C'\fR, \f(CW\*(C`require\*(C'\fR, or \f(CW\*(C`use\*(C'\fR operators. You can
115 switch into a package in more than one place: \f(CW\*(C`package\*(C'\fR has no
116 effect beyond specifying which symbol table the compiler will use for
117 dynamic symbols for the rest of that block or until the next \f(CW\*(C`package\*(C'\fR statement.
118 You can refer to variables and filehandles in other packages
119 by prefixing the identifier with the package name and a double
120 colon: \f(CW$Package::Variable\fR. If the package name is null, the
121 \&\f(CW\*(C`main\*(C'\fR package is assumed. That is, \f(CW$::sail\fR is equivalent to
122 \&\f(CW$main::sail\fR.
123 .PP
124 The old package delimiter was a single quote, but double colon is now the
125 preferred delimiter, in part because it's more readable to humans, and
126 in part because it's more readable to \fBemacs\fR macros. It also makes C++
127 programmers feel like they know what's going on\-\-as opposed to using the
128 single quote as separator, which was there to make Ada programmers feel
129 like they knew what was going on. Because the old-fashioned syntax is still
130 supported for backwards compatibility, if you try to use a string like
131 \&\f(CW"This is $owner\*(Aqs house"\fR, you'll be accessing \f(CW$owner::s\fR; that is,
132 the \f(CW$s\fR variable in package \f(CW\*(C`owner\*(C'\fR, which is probably not what you meant.
133 Use braces to disambiguate, as in \f(CW"This is ${owner}\*(Aqs house"\fR.
134 .IX Xref ":: '"
135 .PP
136 Using \f(CW\*(C`\*(Aq\*(C'\fR as a package separator is deprecated and will be removed in
137 Perl 5.40.
138 .PP
139 Packages may themselves contain package separators, as in
140 \&\f(CW$OUTER::INNER::var\fR. This implies nothing about the order of
141 name lookups, however. There are no relative packages: all symbols
142 are either local to the current package, or must be fully qualified
143 from the outer package name down. For instance, there is nowhere
144 within package \f(CW\*(C`OUTER\*(C'\fR that \f(CW$INNER::var\fR refers to
145 \&\f(CW$OUTER::INNER::var\fR. \f(CW\*(C`INNER\*(C'\fR refers to a totally
146 separate global package. The custom of treating package names as a
147 hierarchy is very strong, but the language in no way enforces it.
148 .PP
149 Only identifiers starting with letters (or underscore) are stored
150 in a package's symbol table. All other symbols are kept in package
151 \&\f(CW\*(C`main\*(C'\fR, including all punctuation variables, like \f(CW$_\fR. In addition,
152 when unqualified, the identifiers STDIN, STDOUT, STDERR, ARGV,
153 ARGVOUT, ENV, INC, and SIG are forced to be in package \f(CW\*(C`main\*(C'\fR,
154 even when used for other purposes than their built-in ones. If you
155 have a package called \f(CW\*(C`m\*(C'\fR, \f(CW\*(C`s\*(C'\fR, or \f(CW\*(C`y\*(C'\fR, then you can't use the
156 qualified form of an identifier because it would be instead interpreted
157 as a pattern match, a substitution, or a transliteration.
158 .IX Xref "variable, punctuation"
159 .PP
160 Variables beginning with underscore used to be forced into package
161 main, but we decided it was more useful for package writers to be able
162 to use leading underscore to indicate private variables and method names.
163 However, variables and functions named with a single \f(CW\*(C`_\*(C'\fR, such as
164 \&\f(CW$_\fR and \f(CW\*(C`sub _\*(C'\fR, are still forced into the package \f(CW\*(C`main\*(C'\fR. See also
165 "The Syntax of Variable Names" in perlvar.
166 .PP
167 \&\f(CW\*(C`eval\*(C'\fRed strings are compiled in the package in which the \fBeval()\fR was
168 compiled. (Assignments to \f(CW\*(C`$SIG{}\*(C'\fR, however, assume the signal
169 handler specified is in the \f(CW\*(C`main\*(C'\fR package. Qualify the signal handler
170 name if you wish to have a signal handler in a package.) For an
171 example, examine \fIperldb.pl\fR in the Perl library. It initially switches
172 to the \f(CW\*(C`DB\*(C'\fR package so that the debugger doesn't interfere with variables
173 in the program you are trying to debug. At various points, however, it
174 temporarily switches back to the \f(CW\*(C`main\*(C'\fR package to evaluate various
175 expressions in the context of the \f(CW\*(C`main\*(C'\fR package (or wherever you came
176 from). See perldebug.
177 .PP
178 The special symbol \f(CW\*(C`_\|_PACKAGE_\|_\*(C'\fR contains the current package, but cannot
179 (easily) be used to construct variable names. After \f(CWmy($foo)\fR has hidden
180 package variable \f(CW$foo\fR, it can still be accessed, without knowing what
181 package you are in, as \f(CW\*(C`${_\|_PACKAGE_\|_.\*(Aq::foo\*(Aq}\*(C'\fR.
182 .PP
183 See perlsub for other scoping issues related to \fBmy()\fR and \fBlocal()\fR,
184 and perlref regarding closures.
185 .SS "Symbol Tables"
186 .IX Xref "symbol table stash %:: %main:: typeglob glob alias"
187 .IX Subsection "Symbol Tables"
188 The symbol table for a package happens to be stored in the hash of that
189 name with two colons appended. The main symbol table's name is thus
190 \&\f(CW%main::\fR, or \f(CW%::\fR for short. Likewise the symbol table for the nested
191 package mentioned earlier is named \f(CW%OUTER::INNER::\fR.
192 .PP
193 The value in each entry of the hash is what you are referring to when you
194 use the \f(CW*name\fR typeglob notation.
195 .PP
196 .Vb 1
197 \& local *main::foo = *main::bar;
198 .Ve
199 .PP
200 You can use this to print out all the variables in a package, for
201 instance. The standard but antiquated \fIdumpvar.pl\fR library and
202 the CPAN module Devel::Symdump make use of this.
203 .PP
204 The results of creating new symbol table entries directly or modifying any
205 entries that are not already typeglobs are undefined and subject to change
206 between releases of perl.
207 .PP
208 Assignment to a typeglob performs an aliasing operation, i.e.,
209 .PP
210 .Vb 1
211 \& *dick = *richard;
212 .Ve
213 .PP
214 causes variables, subroutines, formats, and file and directory handles
215 accessible via the identifier \f(CW\*(C`richard\*(C'\fR also to be accessible via the
216 identifier \f(CW\*(C`dick\*(C'\fR. If you want to alias only a particular variable or
217 subroutine, assign a reference instead:
218 .PP
219 .Vb 1
220 \& *dick = \e$richard;
221 .Ve
222 .PP
223 Which makes \f(CW$richard\fR and \f(CW$dick\fR the same variable, but leaves
224 \&\f(CW@richard\fR and \f(CW@dick\fR as separate arrays. Tricky, eh?
225 .PP
226 There is one subtle difference between the following statements:
227 .PP
228 .Vb 2
229 \& *foo = *bar;
230 \& *foo = \e$bar;
231 .Ve
232 .PP
233 \&\f(CW\*(C`*foo = *bar\*(C'\fR makes the typeglobs themselves synonymous while
234 \&\f(CW\*(C`*foo = \e$bar\*(C'\fR makes the SCALAR portions of two distinct typeglobs
235 refer to the same scalar value. This means that the following code:
236 .PP
237 .Vb 2
238 \& $bar = 1;
239 \& *foo = \e$bar; # Make $foo an alias for $bar
240 \&
241 \& {
242 \& local $bar = 2; # Restrict changes to block
243 \& print $foo; # Prints \*(Aq1\*(Aq!
244 \& }
245 .Ve
246 .PP
247 Would print '1', because \f(CW$foo\fR holds a reference to the \fIoriginal\fR
248 \&\f(CW$bar\fR. The one that was stuffed away by \f(CWlocal()\fR and which will be
249 restored when the block ends. Because variables are accessed through the
250 typeglob, you can use \f(CW\*(C`*foo = *bar\*(C'\fR to create an alias which can be
251 localized. (But be aware that this means you can't have a separate
252 \&\f(CW@foo\fR and \f(CW@bar\fR, etc.)
253 .PP
254 What makes all of this important is that the Exporter module uses glob
255 aliasing as the import/export mechanism. Whether or not you can properly
256 localize a variable that has been exported from a module depends on how
257 it was exported:
258 .PP
259 .Vb 2
260 \& @EXPORT = qw($FOO); # Usual form, can\*(Aqt be localized
261 \& @EXPORT = qw(*FOO); # Can be localized
262 .Ve
263 .PP
264 You can work around the first case by using the fully qualified name
265 (\f(CW$Package::FOO\fR) where you need a local value, or by overriding it
266 by saying \f(CW\*(C`*FOO = *Package::FOO\*(C'\fR in your script.
267 .PP
268 The \f(CW\*(C`*x = \e$y\*(C'\fR mechanism may be used to pass and return cheap references
269 into or from subroutines if you don't want to copy the whole
270 thing. It only works when assigning to dynamic variables, not
271 lexicals.
272 .PP
273 .Vb 9
274 \& %some_hash = (); # can\*(Aqt be my()
275 \& *some_hash = fn( \e%another_hash );
276 \& sub fn {
277 \& local *hashsym = shift;
278 \& # now use %hashsym normally, and you
279 \& # will affect the caller\*(Aqs %another_hash
280 \& my %nhash = (); # do what you want
281 \& return \e%nhash;
282 \& }
283 .Ve
284 .PP
285 On return, the reference will overwrite the hash slot in the
286 symbol table specified by the *some_hash typeglob. This
287 is a somewhat tricky way of passing around references cheaply
288 when you don't want to have to remember to dereference variables
289 explicitly.
290 .PP
291 Another use of symbol tables is for making "constant" scalars.
292 .IX Xref "constant scalar, constant"
293 .PP
294 .Vb 1
295 \& *PI = \e3.14159265358979;
296 .Ve
297 .PP
298 Now you cannot alter \f(CW$PI\fR, which is probably a good thing all in all.
299 This isn't the same as a constant subroutine, which is subject to
300 optimization at compile-time. A constant subroutine is one prototyped
301 to take no arguments and to return a constant expression. See
302 perlsub for details on these. The \f(CW\*(C`use constant\*(C'\fR pragma is a
303 convenient shorthand for these.
304 .PP
305 You can say \f(CW*foo{PACKAGE}\fR and \f(CW*foo{NAME}\fR to find out what name and
306 package the *foo symbol table entry comes from. This may be useful
307 in a subroutine that gets passed typeglobs as arguments:
308 .PP
309 .Vb 7
310 \& sub identify_typeglob {
311 \& my $glob = shift;
312 \& print \*(AqYou gave me \*(Aq, *{$glob}{PACKAGE},
313 \& \*(Aq::\*(Aq, *{$glob}{NAME}, "\en";
314 \& }
315 \& identify_typeglob *foo;
316 \& identify_typeglob *bar::baz;
317 .Ve
318 .PP
319 This prints
320 .PP
321 .Vb 2
322 \& You gave me main::foo
323 \& You gave me bar::baz
324 .Ve
325 .PP
326 The \f(CW*foo{THING}\fR notation can also be used to obtain references to the
327 individual elements of *foo. See perlref.
328 .PP
329 Subroutine definitions (and declarations, for that matter) need
330 not necessarily be situated in the package whose symbol table they
331 occupy. You can define a subroutine outside its package by
332 explicitly qualifying the name of the subroutine:
333 .PP
334 .Vb 2
335 \& package main;
336 \& sub Some_package::foo { ... } # &foo defined in Some_package
337 .Ve
338 .PP
339 This is just a shorthand for a typeglob assignment at compile time:
340 .PP
341 .Vb 1
342 \& BEGIN { *Some_package::foo = sub { ... } }
343 .Ve
344 .PP
345 and is \fInot\fR the same as writing:
346 .PP
347 .Vb 4
348 \& {
349 \& package Some_package;
350 \& sub foo { ... }
351 \& }
352 .Ve
353 .PP
354 In the first two versions, the body of the subroutine is
355 lexically in the main package, \fInot\fR in Some_package. So
356 something like this:
357 .PP
358 .Vb 1
359 \& package main;
360 \&
361 \& $Some_package::name = "fred";
362 \& $main::name = "barney";
363 \&
364 \& sub Some_package::foo {
365 \& print "in ", _\|_PACKAGE_\|_, ": \e$name is \*(Aq$name\*(Aq\en";
366 \& }
367 \&
368 \& Some_package::foo();
369 .Ve
370 .PP
371 prints:
372 .PP
373 .Vb 1
374 \& in main: $name is \*(Aqbarney\*(Aq
375 .Ve
376 .PP
377 rather than:
378 .PP
379 .Vb 1
380 \& in Some_package: $name is \*(Aqfred\*(Aq
381 .Ve
382 .PP
383 This also has implications for the use of the SUPER:: qualifier
384 (see perlobj).
385 .SS "BEGIN, UNITCHECK, CHECK, INIT and END"
386 .IX Xref "BEGIN UNITCHECK CHECK INIT END"
387 .IX Subsection "BEGIN, UNITCHECK, CHECK, INIT and END"
388 Five specially named code blocks are executed at the beginning and at
389 the end of a running Perl program. These are the \f(CW\*(C`BEGIN\*(C'\fR,
390 \&\f(CW\*(C`UNITCHECK\*(C'\fR, \f(CW\*(C`CHECK\*(C'\fR, \f(CW\*(C`INIT\*(C'\fR, and \f(CW\*(C`END\*(C'\fR blocks.
391 .PP
392 These code blocks can be prefixed with \f(CW\*(C`sub\*(C'\fR to give the appearance of a
393 subroutine (although this is not considered good style). One should note
394 that these code blocks don't really exist as named subroutines (despite
395 their appearance). The thing that gives this away is the fact that you can
396 have \fBmore than one\fR of these code blocks in a program, and they will get
397 \&\fBall\fR executed at the appropriate moment. So you can't execute any of
398 these code blocks by name.
399 .PP
400 A \f(CW\*(C`BEGIN\*(C'\fR code block is executed as soon as possible, that is, the moment
401 it is completely defined, even before the rest of the containing file (or
402 string) is parsed. You may have multiple \f(CW\*(C`BEGIN\*(C'\fR blocks within a file (or
403 eval'ed string); they will execute in order of definition. Because a \f(CW\*(C`BEGIN\*(C'\fR
404 code block executes immediately, it can pull in definitions of subroutines
405 and such from other files in time to be visible to the rest of the compile
406 and run time. Once a \f(CW\*(C`BEGIN\*(C'\fR has run, it is immediately undefined and any
407 code it used is returned to Perl's memory pool.
408 .PP
409 An \f(CW\*(C`END\*(C'\fR code block is executed as late as possible, that is, after
410 perl has finished running the program and just before the interpreter
411 is being exited, even if it is exiting as a result of a \fBdie()\fR function.
412 (But not if it's morphing into another program via \f(CW\*(C`exec\*(C'\fR, or
413 being blown out of the water by a signal\-\-you have to trap that yourself
414 (if you can).) You may have multiple \f(CW\*(C`END\*(C'\fR blocks within a file\-\-they
415 will execute in reverse order of definition; that is: last in, first
416 out (LIFO). \f(CW\*(C`END\*(C'\fR blocks are not executed when you run perl with the
417 \&\f(CW\*(C`\-c\*(C'\fR switch, or if compilation fails.
418 .PP
419 Note that \f(CW\*(C`END\*(C'\fR code blocks are \fBnot\fR executed at the end of a string
420 \&\f(CWeval()\fR: if any \f(CW\*(C`END\*(C'\fR code blocks are created in a string \f(CWeval()\fR,
421 they will be executed just as any other \f(CW\*(C`END\*(C'\fR code block of that package
422 in LIFO order just before the interpreter is being exited.
423 .PP
424 Inside an \f(CW\*(C`END\*(C'\fR code block, \f(CW$?\fR contains the value that the program is
425 going to pass to \f(CWexit()\fR. You can modify \f(CW$?\fR to change the exit
426 value of the program. Beware of changing \f(CW$?\fR by accident (e.g. by
427 running something via \f(CW\*(C`system\*(C'\fR).
428 .IX Xref "$?"
429 .PP
430 Inside of a \f(CW\*(C`END\*(C'\fR block, the value of \f(CW\*(C`${^GLOBAL_PHASE}\*(C'\fR will be
431 \&\f(CW"END"\fR.
432 .PP
433 Similar to an \f(CW\*(C`END\*(C'\fR block are \f(CW\*(C`defer\*(C'\fR blocks, though they operate on the
434 lifetime of individual block scopes, rather than the program as a whole. They
435 are documented in "defer" in perlsyn.
436 .PP
437 \&\f(CW\*(C`UNITCHECK\*(C'\fR, \f(CW\*(C`CHECK\*(C'\fR and \f(CW\*(C`INIT\*(C'\fR code blocks are useful to catch the
438 transition between the compilation phase and the execution phase of
439 the main program.
440 .PP
441 \&\f(CW\*(C`UNITCHECK\*(C'\fR blocks are run just after the unit which defined them has
442 been compiled. The main program file and each module it loads are
443 compilation units, as are string \f(CW\*(C`eval\*(C'\fRs, run-time code compiled using the
444 \&\f(CW\*(C`(?{ })\*(C'\fR construct in a regex, calls to \f(CW\*(C`do FILE\*(C'\fR, \f(CW\*(C`require FILE\*(C'\fR,
445 and code after the \f(CW\*(C`\-e\*(C'\fR switch on the command line.
446 .PP
447 \&\f(CW\*(C`BEGIN\*(C'\fR and \f(CW\*(C`UNITCHECK\*(C'\fR blocks are not directly related to the phase of
448 the interpreter. They can be created and executed during any phase.
449 .PP
450 \&\f(CW\*(C`CHECK\*(C'\fR code blocks are run just after the \fBinitial\fR Perl compile phase ends
451 and before the run time begins, in LIFO order. \f(CW\*(C`CHECK\*(C'\fR code blocks are used
452 in the Perl compiler suite to save the compiled state of the program.
453 .PP
454 Inside of a \f(CW\*(C`CHECK\*(C'\fR block, the value of \f(CW\*(C`${^GLOBAL_PHASE}\*(C'\fR will be
455 \&\f(CW"CHECK"\fR.
456 .PP
457 \&\f(CW\*(C`INIT\*(C'\fR blocks are run just before the Perl runtime begins execution, in
458 "first in, first out" (FIFO) order.
459 .PP
460 Inside of an \f(CW\*(C`INIT\*(C'\fR block, the value of \f(CW\*(C`${^GLOBAL_PHASE}\*(C'\fR will be \f(CW"INIT"\fR.
461 .PP
462 The \f(CW\*(C`CHECK\*(C'\fR and \f(CW\*(C`INIT\*(C'\fR blocks in code compiled by \f(CW\*(C`require\*(C'\fR, string \f(CW\*(C`do\*(C'\fR,
463 or string \f(CW\*(C`eval\*(C'\fR will not be executed if they occur after the end of the
464 main compilation phase; that can be a problem in mod_perl and other persistent
465 environments which use those functions to load code at runtime.
466 .PP
467 When you use the \fB\-n\fR and \fB\-p\fR switches to Perl, \f(CW\*(C`BEGIN\*(C'\fR and
468 \&\f(CW\*(C`END\*(C'\fR work just as they do in \fBawk\fR, as a degenerate case.
469 Both \f(CW\*(C`BEGIN\*(C'\fR and \f(CW\*(C`CHECK\*(C'\fR blocks are run when you use the \fB\-c\fR
470 switch for a compile-only syntax check, although your main code
471 is not.
472 .PP
473 The \fBbegincheck\fR program makes it all clear, eventually:
474 .PP
475 .Vb 1
476 \& #!/usr/bin/perl
477 \&
478 \& # begincheck
479 \&
480 \& print "10. Ordinary code runs at runtime.\en";
481 \&
482 \& END { print "16. So this is the end of the tale.\en" }
483 \& INIT { print " 7. INIT blocks run FIFO just before runtime.\en" }
484 \& UNITCHECK {
485 \& print " 4. And therefore before any CHECK blocks.\en"
486 \& }
487 \& CHECK { print " 6. So this is the sixth line.\en" }
488 \&
489 \& print "11. It runs in order, of course.\en";
490 \&
491 \& BEGIN { print " 1. BEGIN blocks run FIFO during compilation.\en" }
492 \& END { print "15. Read perlmod for the rest of the story.\en" }
493 \& CHECK { print " 5. CHECK blocks run LIFO after all compilation.\en" }
494 \& INIT { print " 8. Run this again, using Perl\*(Aqs \-c switch.\en" }
495 \&
496 \& print "12. This is anti\-obfuscated code.\en";
497 \&
498 \& END { print "14. END blocks run LIFO at quitting time.\en" }
499 \& BEGIN { print " 2. So this line comes out second.\en" }
500 \& UNITCHECK {
501 \& print " 3. UNITCHECK blocks run LIFO after each file is compiled.\en"
502 \& }
503 \& INIT { print " 9. You\*(Aqll see the difference right away.\en" }
504 \&
505 \& print "13. It only _looks_ like it should be confusing.\en";
506 \&
507 \& _\|_END_\|_
508 .Ve
509 .SS "Perl Classes"
510 .IX Xref "class @ISA"
511 .IX Subsection "Perl Classes"
512 There is no stable class syntax in Perl, but a package may act
513 as a class if it provides subroutines to act as methods. Such a
514 package may also derive some of its methods from another class (package)
515 by listing the other package name(s) in its global \f(CW@ISA\fR array (which
516 must be a package global, not a lexical).
517 .PP
518 For more on packages acting as classes, see perlootut and perlobj.
519 For more on the not-yet-stable class syntax, see perlclass.
520 .SS "Perl Modules"
521 .IX Xref "module"
522 .IX Subsection "Perl Modules"
523 A module is just a set of related functions in a library file, i.e.,
524 a Perl package with the same name as the file. It is specifically
525 designed to be reusable by other modules or programs. It may do this
526 by providing a mechanism for exporting some of its symbols into the
527 symbol table of any package using it, or it may function as a class
528 definition and make its semantics available implicitly through
529 method calls on the class and its objects, without explicitly
530 exporting anything. Or it can do a little of both.
531 .PP
532 For example, to start a traditional, non-OO module called Some::Module,
533 create a file called \fISome/Module.pm\fR and start with this template:
534 .PP
535 .Vb 1
536 \& package Some::Module; # assumes Some/Module.pm
537 \&
538 \& use v5.36;
539 \&
540 \& # Get the import method from Exporter to export functions and
541 \& # variables
542 \& use Exporter 5.57 \*(Aqimport\*(Aq;
543 \&
544 \& # set the version for version checking
545 \& our $VERSION = \*(Aq1.00\*(Aq;
546 \&
547 \& # Functions and variables which are exported by default
548 \& our @EXPORT = qw(func1 func2);
549 \&
550 \& # Functions and variables which can be optionally exported
551 \& our @EXPORT_OK = qw($Var1 %Hashit func3);
552 \&
553 \& # exported package globals go here
554 \& our $Var1 = \*(Aq\*(Aq;
555 \& our %Hashit = ();
556 \&
557 \& # non\-exported package globals go here
558 \& # (they are still accessible as $Some::Module::stuff)
559 \& our @more = ();
560 \& our $stuff = \*(Aq\*(Aq;
561 \&
562 \& # file\-private lexicals go here, before any functions which use them
563 \& my $priv_var = \*(Aq\*(Aq;
564 \& my %secret_hash = ();
565 \&
566 \& # here\*(Aqs a file\-private function as a closure,
567 \& # callable as $priv_func\->();
568 \& my $priv_func = sub {
569 \& ...
570 \& };
571 \&
572 \& # make all your functions, whether exported or not;
573 \& # remember to put something interesting in the {} stubs
574 \& sub func1 { ... }
575 \& sub func2 { ... }
576 \&
577 \& # this one isn\*(Aqt always exported, but could be called directly
578 \& # as Some::Module::func3()
579 \& sub func3 { ... }
580 \&
581 \& END { ... } # module clean\-up code here (global destructor)
582 \&
583 \& 1; # don\*(Aqt forget to return a true value from the file
584 .Ve
585 .PP
586 Then go on to declare and use your variables in functions without
587 any qualifications. See Exporter and the perlmodlib for
588 details on mechanics and style issues in module creation.
589 .PP
590 Perl modules are included into your program by saying
591 .PP
592 .Vb 1
593 \& use Module;
594 .Ve
595 .PP
596 or
597 .PP
598 .Vb 1
599 \& use Module LIST;
600 .Ve
601 .PP
602 This is exactly equivalent to
603 .PP
604 .Vb 1
605 \& BEGIN { require \*(AqModule.pm\*(Aq; \*(AqModule\*(Aq\->import; }
606 .Ve
607 .PP
608 or
609 .PP
610 .Vb 1
611 \& BEGIN { require \*(AqModule.pm\*(Aq; \*(AqModule\*(Aq\->import( LIST ); }
612 .Ve
613 .PP
614 As a special case
615 .PP
616 .Vb 1
617 \& use Module ();
618 .Ve
619 .PP
620 is exactly equivalent to
621 .PP
622 .Vb 1
623 \& BEGIN { require \*(AqModule.pm\*(Aq; }
624 .Ve
625 .PP
626 All Perl module files have the extension \fI.pm\fR. The \f(CW\*(C`use\*(C'\fR operator
627 assumes this so you don't have to spell out "\fIModule.pm\fR" in quotes.
628 This also helps to differentiate new modules from old \fI.pl\fR and
629 \&\fI.ph\fR files. Module names are also capitalized unless they're
630 functioning as pragmas; pragmas are in effect compiler directives,
631 and are sometimes called "pragmatic modules" (or even "pragmata"
632 if you're a classicist).
633 .PP
634 The two statements:
635 .PP
636 .Vb 2
637 \& require SomeModule;
638 \& require "SomeModule.pm";
639 .Ve
640 .PP
641 differ from each other in two ways. In the first case, any double
642 colons in the module name, such as \f(CW\*(C`Some::Module\*(C'\fR, are translated
643 into your system's directory separator, usually "/". The second
644 case does not, and would have to be specified literally. The other
645 difference is that seeing the first \f(CW\*(C`require\*(C'\fR clues in the compiler
646 that uses of indirect object notation involving "SomeModule", as
647 in \f(CW\*(C`$ob = purge SomeModule\*(C'\fR, are method calls, not function calls.
648 (Yes, this really can make a difference.)
649 .PP
650 Because the \f(CW\*(C`use\*(C'\fR statement implies a \f(CW\*(C`BEGIN\*(C'\fR block, the importing
651 of semantics happens as soon as the \f(CW\*(C`use\*(C'\fR statement is compiled,
652 before the rest of the file is compiled. This is how it is able
653 to function as a pragma mechanism, and also how modules are able to
654 declare subroutines that are then visible as list or unary operators for
655 the rest of the current file. This will not work if you use \f(CW\*(C`require\*(C'\fR
656 instead of \f(CW\*(C`use\*(C'\fR. With \f(CW\*(C`require\*(C'\fR you can get into this problem:
657 .PP
658 .Vb 2
659 \& require Cwd; # make Cwd:: accessible
660 \& $here = Cwd::getcwd();
661 \&
662 \& use Cwd; # import names from Cwd::
663 \& $here = getcwd();
664 \&
665 \& require Cwd; # make Cwd:: accessible
666 \& $here = getcwd(); # oops! no main::getcwd()
667 .Ve
668 .PP
669 In general, \f(CW\*(C`use Module ()\*(C'\fR is recommended over \f(CW\*(C`require Module\*(C'\fR,
670 because it determines module availability at compile time, not in the
671 middle of your program's execution. An exception would be if two modules
672 each tried to \f(CW\*(C`use\*(C'\fR each other, and each also called a function from
673 that other module. In that case, it's easy to use \f(CW\*(C`require\*(C'\fR instead.
674 .PP
675 Perl packages may be nested inside other package names, so we can have
676 package names containing \f(CW\*(C`::\*(C'\fR. But if we used that package name
677 directly as a filename it would make for unwieldy or impossible
678 filenames on some systems. Therefore, if a module's name is, say,
679 \&\f(CW\*(C`Text::Soundex\*(C'\fR, then its definition is actually found in the library
680 file \fIText/Soundex.pm\fR.
681 .PP
682 Perl modules always have a \fI.pm\fR file, but there may also be
683 dynamically linked executables (often ending in \fI.so\fR) or autoloaded
684 subroutine definitions (often ending in \fI.al\fR) associated with the
685 module. If so, these will be entirely transparent to the user of
686 the module. It is the responsibility of the \fI.pm\fR file to load
687 (or arrange to autoload) any additional functionality. For example,
688 although the POSIX module happens to do both dynamic loading and
689 autoloading, the user can say just \f(CW\*(C`use POSIX\*(C'\fR to get it all.
690 .SS "Making your module threadsafe"
691 .IX Xref "threadsafe thread safe module, threadsafe module, thread safe CLONE CLONE_SKIP thread threads ithread"
692 .IX Subsection "Making your module threadsafe"
693 Perl supports a type of threads called interpreter threads (ithreads).
694 These threads can be used explicitly and implicitly.
695 .PP
696 Ithreads work by cloning the data tree so that no data is shared
697 between different threads. These threads can be used by using the \f(CW\*(C`threads\*(C'\fR
698 module or by doing \fBfork()\fR on win32 (fake \fBfork()\fR support). When a
699 thread is cloned all Perl data is cloned, however non-Perl data cannot
700 be cloned automatically. Perl after 5.8.0 has support for the \f(CW\*(C`CLONE\*(C'\fR
701 special subroutine. In \f(CW\*(C`CLONE\*(C'\fR you can do whatever
702 you need to do,
703 like for example handle the cloning of non-Perl data, if necessary.
704 \&\f(CW\*(C`CLONE\*(C'\fR will be called once as a class method for every package that has it
705 defined (or inherits it). It will be called in the context of the new thread,
706 so all modifications are made in the new area. Currently CLONE is called with
707 no parameters other than the invocant package name, but code should not assume
708 that this will remain unchanged, as it is likely that in future extra parameters
709 will be passed in to give more information about the state of cloning.
710 .PP
711 If you want to CLONE all objects you will need to keep track of them per
712 package. This is simply done using a hash and \fBScalar::Util::weaken()\fR.
713 .PP
714 Perl after 5.8.7 has support for the \f(CW\*(C`CLONE_SKIP\*(C'\fR special subroutine.
715 Like \f(CW\*(C`CLONE\*(C'\fR, \f(CW\*(C`CLONE_SKIP\*(C'\fR is called once per package; however, it is
716 called just before cloning starts, and in the context of the parent
717 thread. If it returns a true value, then no objects of that class will
718 be cloned; or rather, they will be copied as unblessed, undef values.
719 For example: if in the parent there are two references to a single blessed
720 hash, then in the child there will be two references to a single undefined
721 scalar value instead.
722 This provides a simple mechanism for making a module threadsafe; just add
723 \&\f(CW\*(C`sub CLONE_SKIP { 1 }\*(C'\fR at the top of the class, and \f(CWDESTROY()\fR will
724 now only be called once per object. Of course, if the child thread needs
725 to make use of the objects, then a more sophisticated approach is
726 needed.
727 .PP
728 Like \f(CW\*(C`CLONE\*(C'\fR, \f(CW\*(C`CLONE_SKIP\*(C'\fR is currently called with no parameters other
729 than the invocant package name, although that may change. Similarly, to
730 allow for future expansion, the return value should be a single \f(CW0\fR or
731 \&\f(CW1\fR value.
732 .SH "SEE ALSO"
733 .IX Header "SEE ALSO"
734 See perlmodlib for general style issues related to building Perl
735 modules and classes, as well as descriptions of the standard library
736 and CPAN, Exporter for how Perl's standard import/export mechanism
737 works, perlootut and perlobj for in-depth information on
738 creating classes, perlobj for a hard-core reference document on
739 objects, perlsub for an explanation of functions and scoping,
740 and perlxstut and perlguts for more information on writing
741 extension modules.