Debian Codegraph @

upstream/mageia-cauldron/man1/perlmod.1

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