Debian Codegraph @

upstream/debian-unstable/man1/perlsub.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 "PERLSUB 1"
58 .TH PERLSUB 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 perlsub \- Perl subroutines (user\-defined functions)
65 .IX Xref "subroutine function"
66 .SH SYNOPSIS
67 .IX Header "SYNOPSIS"
68 To declare subroutines:
69 .IX Xref "subroutine, declaration sub"
70 .PP
71 .Vb 4
72 \& sub NAME; # A "forward" declaration.
73 \& sub NAME(PROTO); # ditto, but with prototypes
74 \& sub NAME : ATTRS; # with attributes
75 \& sub NAME(PROTO) : ATTRS; # with attributes and prototypes
76 \&
77 \& sub NAME BLOCK # A declaration and a definition.
78 \& sub NAME(PROTO) BLOCK # ditto, but with prototypes
79 \& sub NAME : ATTRS BLOCK # with attributes
80 \& sub NAME(PROTO) : ATTRS BLOCK # with prototypes and attributes
81 \&
82 \& use feature \*(Aqsignatures\*(Aq;
83 \& sub NAME(SIG) BLOCK # with signature
84 \& sub NAME :ATTRS (SIG) BLOCK # with signature, attributes
85 \& sub NAME :prototype(PROTO) (SIG) BLOCK # with signature, prototype
86 .Ve
87 .PP
88 To define an anonymous subroutine at runtime:
89 .IX Xref "subroutine, anonymous"
90 .PP
91 .Vb 4
92 \& $subref = sub BLOCK; # no proto
93 \& $subref = sub (PROTO) BLOCK; # with proto
94 \& $subref = sub : ATTRS BLOCK; # with attributes
95 \& $subref = sub (PROTO) : ATTRS BLOCK; # with proto and attributes
96 \&
97 \& use feature \*(Aqsignatures\*(Aq;
98 \& $subref = sub (SIG) BLOCK; # with signature
99 \& $subref = sub : ATTRS(SIG) BLOCK; # with signature, attributes
100 .Ve
101 .PP
102 To import subroutines:
103 .IX Xref "import"
104 .PP
105 .Vb 1
106 \& use MODULE qw(NAME1 NAME2 NAME3);
107 .Ve
108 .PP
109 To call subroutines:
110 .IX Xref "subroutine, call call"
111 .PP
112 .Vb 4
113 \& NAME(LIST); # Regular subroutine call.
114 \& NAME LIST; # Parentheses optional if predeclared/imported.
115 \& &NAME(LIST); # Circumvent prototypes.
116 \& &NAME; # Makes current @_ visible to called subroutine.
117 .Ve
118 .SH DESCRIPTION
119 .IX Header "DESCRIPTION"
120 Like many languages, Perl provides for user-defined subroutines.
121 These may be located anywhere in the main program, loaded in from
122 other files via the \f(CW\*(C`do\*(C'\fR, \f(CW\*(C`require\*(C'\fR, or \f(CW\*(C`use\*(C'\fR keywords, or
123 generated on the fly using \f(CW\*(C`eval\*(C'\fR or anonymous subroutines.
124 You can even call a function indirectly using a variable containing
125 its name or a CODE reference.
126 .PP
127 The Perl model for function call and return values is simple: all
128 functions are passed as parameters one single flat list of scalars, and
129 all functions likewise return to their caller one single flat list of
130 scalars. Any arrays or hashes in these call and return lists will
131 collapse, losing their identities\-\-but you may always use
132 pass-by-reference instead to avoid this. Both call and return lists may
133 contain as many or as few scalar elements as you'd like. (Often a
134 function without an explicit return statement is called a subroutine, but
135 there's really no difference from Perl's perspective.)
136 .IX Xref "subroutine, parameter parameter"
137 .PP
138 In a subroutine that uses signatures (see "Signatures" below),
139 arguments are assigned into lexical variables introduced by the
140 signature. In the current implementation of Perl they are also
141 accessible in the \f(CW@_\fR array in the same way as for non-signature
142 subroutines, but accessing them in this manner is now discouraged inside
143 such a signature-using subroutine.
144 .PP
145 In a subroutine that does not use signatures, any arguments passed in
146 show up in the array \f(CW@_\fR. Therefore, if you called a function with
147 two arguments, those would be stored in \f(CW$_[0]\fR and \f(CW$_[1]\fR. The
148 array \f(CW@_\fR is a local array, but its elements are aliases for the
149 actual scalar parameters. In particular, if an element \f(CW$_[0]\fR is
150 updated, the corresponding argument is updated (or an error occurs if it
151 is not updatable). If an argument is an array or hash element which did
152 not exist when the function was called, that element is created only
153 when (and if) it is modified or a reference to it is taken. (Some
154 earlier versions of Perl created the element whether or not the element
155 was assigned to.) Assigning to the whole array \f(CW@_\fR removes that
156 aliasing, and does not update any arguments.
157 .IX Xref "subroutine, argument argument @_"
158 .PP
159 When not using signatures, Perl does not otherwise provide a means to
160 create named formal parameters. In practice all you do is assign to a
161 \&\f(CWmy()\fR list of these. Variables that aren't declared to be private are
162 global variables. For gory details on creating private variables, see
163 "Private Variables via \fBmy()\fR" and "Temporary Values via \fBlocal()\fR".
164 To create protected environments for a set of functions in a separate
165 package (and probably a separate file), see "Packages" in perlmod.
166 .PP
167 A \f(CW\*(C`return\*(C'\fR statement may be used to exit a subroutine, optionally
168 specifying the returned value, which will be evaluated in the
169 appropriate context (list, scalar, or void) depending on the context of
170 the subroutine call. If you specify no return value, the subroutine
171 returns an empty list in list context, the undefined value in scalar
172 context, or nothing in void context. If you return one or more
173 aggregates (arrays and hashes), these will be flattened together into
174 one large indistinguishable list.
175 .PP
176 If no \f(CW\*(C`return\*(C'\fR is found and if the last statement is an expression, its
177 value is returned. If the last statement is a loop control structure
178 like a \f(CW\*(C`foreach\*(C'\fR or a \f(CW\*(C`while\*(C'\fR, the returned value is unspecified. The
179 empty sub returns the empty list.
180 .IX Xref "subroutine, return value return value return"
181 .PP
182 Example:
183 .PP
184 .Vb 8
185 \& sub max {
186 \& my $max = shift(@_);
187 \& foreach $foo (@_) {
188 \& $max = $foo if $max < $foo;
189 \& }
190 \& return $max;
191 \& }
192 \& $bestday = max($mon,$tue,$wed,$thu,$fri);
193 .Ve
194 .PP
195 Example:
196 .PP
197 .Vb 2
198 \& # get a line, combining continuation lines
199 \& # that start with whitespace
200 \&
201 \& sub get_line {
202 \& $thisline = $lookahead; # global variables!
203 \& LINE: while (defined($lookahead = <STDIN>)) {
204 \& if ($lookahead =~ /^[ \et]/) {
205 \& $thisline .= $lookahead;
206 \& }
207 \& else {
208 \& last LINE;
209 \& }
210 \& }
211 \& return $thisline;
212 \& }
213 \&
214 \& $lookahead = <STDIN>; # get first line
215 \& while (defined($line = get_line())) {
216 \& ...
217 \& }
218 .Ve
219 .PP
220 Assigning to a list of private variables to name your arguments:
221 .PP
222 .Vb 4
223 \& sub maybeset {
224 \& my($key, $value) = @_;
225 \& $Foo{$key} = $value unless $Foo{$key};
226 \& }
227 .Ve
228 .PP
229 Because the assignment copies the values, this also has the effect
230 of turning call-by-reference into call-by-value. Otherwise a
231 function is free to do in-place modifications of \f(CW@_\fR and change
232 its caller's values.
233 .IX Xref "call-by-reference call-by-value"
234 .PP
235 .Vb 4
236 \& upcase_in($v1, $v2); # this changes $v1 and $v2
237 \& sub upcase_in {
238 \& for (@_) { tr/a\-z/A\-Z/ }
239 \& }
240 .Ve
241 .PP
242 You aren't allowed to modify constants in this way, of course. If an
243 argument were actually literal and you tried to change it, you'd take a
244 (presumably fatal) exception. For example, this won't work:
245 .IX Xref "call-by-reference call-by-value"
246 .PP
247 .Vb 1
248 \& upcase_in("frederick");
249 .Ve
250 .PP
251 It would be much safer if the \f(CWupcase_in()\fR function
252 were written to return a copy of its parameters instead
253 of changing them in place:
254 .PP
255 .Vb 7
256 \& ($v3, $v4) = upcase($v1, $v2); # this doesn\*(Aqt change $v1 and $v2
257 \& sub upcase {
258 \& return unless defined wantarray; # void context, do nothing
259 \& my @parms = @_;
260 \& for (@parms) { tr/a\-z/A\-Z/ }
261 \& return wantarray ? @parms : $parms[0];
262 \& }
263 .Ve
264 .PP
265 Notice how this (unprototyped) function doesn't care whether it was
266 passed real scalars or arrays. Perl sees all arguments as one big,
267 long, flat parameter list in \f(CW@_\fR. This is one area where
268 Perl's simple argument-passing style shines. The \f(CWupcase()\fR
269 function would work perfectly well without changing the \f(CWupcase()\fR
270 definition even if we fed it things like this:
271 .PP
272 .Vb 2
273 \& @newlist = upcase(@list1, @list2);
274 \& @newlist = upcase( split /:/, $var );
275 .Ve
276 .PP
277 Do not, however, be tempted to do this:
278 .PP
279 .Vb 1
280 \& (@x, @y) = upcase(@list1, @list2);
281 .Ve
282 .PP
283 Like the flattened incoming parameter list, the return list is also
284 flattened on return. So all you have managed to do here is stored
285 everything in \f(CW@x\fR and made \f(CW@y\fR empty. See
286 "Pass by Reference" for alternatives.
287 .PP
288 A subroutine may be called using an explicit \f(CW\*(C`&\*(C'\fR prefix. The
289 \&\f(CW\*(C`&\*(C'\fR is optional in modern Perl, as are parentheses if the
290 subroutine has been predeclared. The \f(CW\*(C`&\*(C'\fR is \fInot\fR optional
291 when just naming the subroutine, such as when it's used as
292 an argument to \fBdefined()\fR or \fBundef()\fR. Nor is it optional when you
293 want to do an indirect subroutine call with a subroutine name or
294 reference using the \f(CW&$subref()\fR or \f(CW\*(C`&{$subref}()\*(C'\fR constructs,
295 although the \f(CW$subref\->()\fR notation solves that problem.
296 See perlref for more about all that.
297 .IX Xref "&"
298 .PP
299 Subroutines may be called recursively. If a subroutine is called
300 using the \f(CW\*(C`&\*(C'\fR form, the argument list is optional, and if omitted,
301 no \f(CW@_\fR array is set up for the subroutine: the \f(CW@_\fR array at the
302 time of the call is visible to subroutine instead. This is an
303 efficiency mechanism that new users may wish to avoid.
304 .IX Xref "recursion"
305 .PP
306 .Vb 2
307 \& &foo(1,2,3); # pass three arguments
308 \& foo(1,2,3); # the same
309 \&
310 \& foo(); # pass an empty argument list
311 \& &foo(); # the same
312 \&
313 \& &foo; # foo() gets current args, like foo(@_)!
314 \& use strict \*(Aqsubs\*(Aq;
315 \& foo; # like foo() iff sub foo predeclared, else
316 \& # a compile\-time error
317 \& no strict \*(Aqsubs\*(Aq;
318 \& foo; # like foo() iff sub foo predeclared, else
319 \& # a literal string "foo"
320 .Ve
321 .PP
322 Not only does the \f(CW\*(C`&\*(C'\fR form make the argument list optional, it also
323 disables any prototype checking on arguments you do provide. This
324 is partly for historical reasons, and partly for having a convenient way
325 to cheat if you know what you're doing. See "Prototypes" below.
326 .IX Xref "&"
327 .PP
328 Since Perl 5.16.0, the \f(CW\*(C`_\|_SUB_\|_\*(C'\fR token is available under \f(CWuse feature
329 \&\*(Aqcurrent_sub\*(Aq\fR and \f(CW\*(C`use v5.16\*(C'\fR. It will evaluate to a reference to the
330 currently-running sub, which allows for recursive calls without knowing
331 your subroutine's name.
332 .PP
333 .Vb 6
334 \& use v5.16;
335 \& my $factorial = sub {
336 \& my ($x) = @_;
337 \& return 1 if $x == 1;
338 \& return($x * _\|_SUB_\|_\->( $x \- 1 ) );
339 \& };
340 .Ve
341 .PP
342 The behavior of \f(CW\*(C`_\|_SUB_\|_\*(C'\fR within a regex code block (such as \f(CW\*(C`/(?{...})/\*(C'\fR)
343 is subject to change.
344 .PP
345 Subroutines whose names are in all upper case are reserved to the Perl
346 core, as are modules whose names are in all lower case. A subroutine in
347 all capitals is a loosely-held convention meaning it will be called
348 indirectly by the run-time system itself, usually due to a triggered event.
349 Subroutines whose name start with a left parenthesis are also reserved the
350 same way. The following is a list of some subroutines that currently do
351 special, pre-defined things.
352 .IP "documented later in this document" 4
353 .IX Item "documented later in this document"
354 \&\f(CW\*(C`AUTOLOAD\*(C'\fR
355 .IP "documented in perlmod" 4
356 .IX Item "documented in perlmod"
357 \&\f(CW\*(C`CLONE\*(C'\fR, \f(CW\*(C`CLONE_SKIP\*(C'\fR
358 .IP "documented in perlobj" 4
359 .IX Item "documented in perlobj"
360 \&\f(CW\*(C`DESTROY\*(C'\fR, \f(CW\*(C`DOES\*(C'\fR
361 .IP "documented in perltie" 4
362 .IX Item "documented in perltie"
363 \&\f(CW\*(C`BINMODE\*(C'\fR, \f(CW\*(C`CLEAR\*(C'\fR, \f(CW\*(C`CLOSE\*(C'\fR, \f(CW\*(C`DELETE\*(C'\fR, \f(CW\*(C`DESTROY\*(C'\fR, \f(CW\*(C`EOF\*(C'\fR, \f(CW\*(C`EXISTS\*(C'\fR,
364 \&\f(CW\*(C`EXTEND\*(C'\fR, \f(CW\*(C`FETCH\*(C'\fR, \f(CW\*(C`FETCHSIZE\*(C'\fR, \f(CW\*(C`FILENO\*(C'\fR, \f(CW\*(C`FIRSTKEY\*(C'\fR, \f(CW\*(C`GETC\*(C'\fR,
365 \&\f(CW\*(C`NEXTKEY\*(C'\fR, \f(CW\*(C`OPEN\*(C'\fR, \f(CW\*(C`POP\*(C'\fR, \f(CW\*(C`PRINT\*(C'\fR, \f(CW\*(C`PRINTF\*(C'\fR, \f(CW\*(C`PUSH\*(C'\fR, \f(CW\*(C`READ\*(C'\fR,
366 \&\f(CW\*(C`READLINE\*(C'\fR, \f(CW\*(C`SCALAR\*(C'\fR, \f(CW\*(C`SEEK\*(C'\fR, \f(CW\*(C`SHIFT\*(C'\fR, \f(CW\*(C`SPLICE\*(C'\fR, \f(CW\*(C`STORE\*(C'\fR,
367 \&\f(CW\*(C`STORESIZE\*(C'\fR, \f(CW\*(C`TELL\*(C'\fR, \f(CW\*(C`TIEARRAY\*(C'\fR, \f(CW\*(C`TIEHANDLE\*(C'\fR, \f(CW\*(C`TIEHASH\*(C'\fR,
368 \&\f(CW\*(C`TIESCALAR\*(C'\fR, \f(CW\*(C`UNSHIFT\*(C'\fR, \f(CW\*(C`UNTIE\*(C'\fR, \f(CW\*(C`WRITE\*(C'\fR
369 .IP "documented in PerlIO::via" 4
370 .IX Item "documented in PerlIO::via"
371 \&\f(CW\*(C`BINMODE\*(C'\fR, \f(CW\*(C`CLEARERR\*(C'\fR, \f(CW\*(C`CLOSE\*(C'\fR, \f(CW\*(C`EOF\*(C'\fR, \f(CW\*(C`ERROR\*(C'\fR, \f(CW\*(C`FDOPEN\*(C'\fR, \f(CW\*(C`FILENO\*(C'\fR,
372 \&\f(CW\*(C`FILL\*(C'\fR, \f(CW\*(C`FLUSH\*(C'\fR, \f(CW\*(C`OPEN\*(C'\fR, \f(CW\*(C`POPPED\*(C'\fR, \f(CW\*(C`PUSHED\*(C'\fR, \f(CW\*(C`READ\*(C'\fR, \f(CW\*(C`SEEK\*(C'\fR,
373 \&\f(CW\*(C`SETLINEBUF\*(C'\fR, \f(CW\*(C`SYSOPEN\*(C'\fR, \f(CW\*(C`TELL\*(C'\fR, \f(CW\*(C`UNREAD\*(C'\fR, \f(CW\*(C`UTF8\*(C'\fR, \f(CW\*(C`WRITE\*(C'\fR
374 .IP "documented in perlfunc" 4
375 .IX Item "documented in perlfunc"
376 \&\f(CW\*(C`import\*(C'\fR, \f(CW\*(C`unimport\*(C'\fR,
377 \&\f(CW\*(C`INC\*(C'\fR
378 .IP "documented in UNIVERSAL" 4
379 .IX Item "documented in UNIVERSAL"
380 \&\f(CW\*(C`VERSION\*(C'\fR
381 .IP "documented in perldebguts" 4
382 .IX Item "documented in perldebguts"
383 \&\f(CW\*(C`DB::DB\*(C'\fR, \f(CW\*(C`DB::sub\*(C'\fR, \f(CW\*(C`DB::lsub\*(C'\fR, \f(CW\*(C`DB::goto\*(C'\fR, \f(CW\*(C`DB::postponed\*(C'\fR
384 .IP "undocumented, used internally by the overload feature" 4
385 .IX Item "undocumented, used internally by the overload feature"
386 any starting with \f(CW\*(C`(\*(C'\fR
387 .PP
388 The \f(CW\*(C`BEGIN\*(C'\fR, \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 subroutines
389 are not so much subroutines as named special code blocks, of which you
390 can have more than one in a package, and which you can \fBnot\fR call
391 explicitly. See "BEGIN, UNITCHECK, CHECK, INIT and END" in perlmod
392 .SS Signatures
393 .IX Subsection "Signatures"
394
395 .IX Xref "formal parameter parameter, formal"
396 .PP
397 Perl has a facility to allow a subroutine's formal parameters to be
398 declared by special syntax, separate from the procedural code of the
399 subroutine body. The formal parameter list is known as a \fIsignature\fR.
400 .PP
401 This facility must be enabled before it can be used. It is enabled
402 automatically by a \f(CW\*(C`use v5.36\*(C'\fR (or higher) declaration, or more
403 directly by \f(CW\*(C`use feature \*(Aqsignatures\*(Aq\*(C'\fR, in the current scope.
404 .PP
405 The signature is part of a subroutine's body. Normally the body of a
406 subroutine is simply a braced block of code, but when using a signature,
407 the signature is a parenthesised list that goes immediately before the
408 block, after any name or attributes.
409 .PP
410 For example,
411 .PP
412 .Vb 1
413 \& sub foo :lvalue ($x, $y = 1, @z) { .... }
414 .Ve
415 .PP
416 The signature declares lexical variables that are
417 in scope for the block. When the subroutine is called, the signature
418 takes control first. It populates the signature variables from the
419 list of arguments that were passed. If the argument list doesn't meet
420 the requirements of the signature, then it will throw an exception.
421 When the signature processing is complete, control passes to the block.
422 .PP
423 Positional parameters are handled by simply naming scalar variables in
424 the signature. For example,
425 .PP
426 .Vb 3
427 \& sub foo ($left, $right) {
428 \& return $left + $right;
429 \& }
430 .Ve
431 .PP
432 takes two positional parameters, which must be filled at runtime by
433 two arguments. By default the parameters are mandatory, and it is
434 not permitted to pass more arguments than expected. So the above is
435 equivalent to
436 .PP
437 .Vb 7
438 \& sub foo {
439 \& die "Too many arguments for subroutine" unless @_ <= 2;
440 \& die "Too few arguments for subroutine" unless @_ >= 2;
441 \& my $left = $_[0];
442 \& my $right = $_[1];
443 \& return $left + $right;
444 \& }
445 .Ve
446 .PP
447 An argument can be ignored by omitting the main part of the name from
448 a parameter declaration, leaving just a bare \f(CW\*(C`$\*(C'\fR sigil. For example,
449 .PP
450 .Vb 3
451 \& sub foo ($first, $, $third) {
452 \& return "first=$first, third=$third";
453 \& }
454 .Ve
455 .PP
456 Although the ignored argument doesn't go into a variable, it is still
457 mandatory for the caller to pass it.
458 .PP
459 A positional parameter is made optional by giving a default value,
460 separated from the parameter name by \f(CW\*(C`=\*(C'\fR:
461 .PP
462 .Vb 3
463 \& sub foo ($left, $right = 0) {
464 \& return $left + $right;
465 \& }
466 .Ve
467 .PP
468 The above subroutine may be called with either one or two arguments.
469 The default value expression is evaluated when the subroutine is called,
470 so it may provide different default values for different calls. It is
471 only evaluated if the argument was actually omitted from the call.
472 For example,
473 .PP
474 .Vb 4
475 \& my $auto_id = 0;
476 \& sub foo ($thing, $id = $auto_id++) {
477 \& print "$thing has ID $id";
478 \& }
479 .Ve
480 .PP
481 automatically assigns distinct sequential IDs to things for which no
482 ID was supplied by the caller. A default value expression may also
483 refer to parameters earlier in the signature, making the default for
484 one parameter vary according to the earlier parameters. For example,
485 .PP
486 .Vb 3
487 \& sub foo ($first_name, $surname, $nickname = $first_name) {
488 \& print "$first_name $surname is known as \e"$nickname\e"";
489 \& }
490 .Ve
491 .PP
492 A default value expression can also be written using the \f(CW\*(C`//=\*(C'\fR operator,
493 where it will be evaluated and used if the caller omitted a value or the
494 value provided was \f(CW\*(C`undef\*(C'\fR.
495 .PP
496 .Vb 3
497 \& sub foo ($name //= "world") {
498 \& print "Hello, $name";
499 \& }
500 \&
501 \& foo(undef); # will print "Hello, world"
502 .Ve
503 .PP
504 Similarly, the \f(CW\*(C`||=\*(C'\fR operator can be used to provide a default
505 expression to be used whenever the caller provided a false value (and
506 remember that a missing or \f(CW\*(C`undef\*(C'\fR value are also false).
507 .PP
508 .Vb 3
509 \& sub foo ($x ||= 10) {
510 \& return 5 + $x;
511 \& }
512 .Ve
513 .PP
514 An optional parameter can be nameless just like a mandatory parameter.
515 For example,
516 .PP
517 .Vb 3
518 \& sub foo ($thing, $ = 1) {
519 \& print $thing;
520 \& }
521 .Ve
522 .PP
523 The parameter's default value will still be evaluated if the corresponding
524 argument isn't supplied, even though the value won't be stored anywhere.
525 This is in case evaluating it has important side effects. However, it
526 will be evaluated in void context, so if it doesn't have side effects
527 and is not trivial it will generate a warning if the "void" warning
528 category is enabled. If a nameless optional parameter's default value
529 is not important, it may be omitted just as the parameter's name was:
530 .PP
531 .Vb 3
532 \& sub foo ($thing, $=) {
533 \& print $thing;
534 \& }
535 .Ve
536 .PP
537 Optional positional parameters must come after all mandatory positional
538 parameters. (If there are no mandatory positional parameters then an
539 optional positional parameters can be the first thing in the signature.)
540 If there are multiple optional positional parameters and not enough
541 arguments are supplied to fill them all, they will be filled from left
542 to right.
543 .PP
544 After positional parameters, additional arguments may be captured in a
545 slurpy parameter. The simplest form of this is just an array variable:
546 .PP
547 .Vb 3
548 \& sub foo ($filter, @inputs) {
549 \& print $filter\->($_) foreach @inputs;
550 \& }
551 .Ve
552 .PP
553 With a slurpy parameter in the signature, there is no upper limit on how
554 many arguments may be passed. A slurpy array parameter may be nameless
555 just like a positional parameter, in which case its only effect is to
556 turn off the argument limit that would otherwise apply:
557 .PP
558 .Vb 3
559 \& sub foo ($thing, @) {
560 \& print $thing;
561 \& }
562 .Ve
563 .PP
564 A slurpy parameter may instead be a hash, in which case the arguments
565 available to it are interpreted as alternating keys and values.
566 There must be as many keys as values: if there is an odd argument then
567 an exception will be thrown. Keys will be stringified, and if there are
568 duplicates then the later instance takes precedence over the earlier,
569 as with standard hash construction.
570 .PP
571 .Vb 3
572 \& sub foo ($filter, %inputs) {
573 \& print $filter\->($_, $inputs{$_}) foreach sort keys %inputs;
574 \& }
575 .Ve
576 .PP
577 A slurpy hash parameter may be nameless just like other kinds of
578 parameter. It still insists that the number of arguments available to
579 it be even, even though they're not being put into a variable.
580 .PP
581 .Vb 3
582 \& sub foo ($thing, %) {
583 \& print $thing;
584 \& }
585 .Ve
586 .PP
587 A slurpy parameter, either array or hash, must be the last thing in the
588 signature. It may follow mandatory and optional positional parameters;
589 it may also be the only thing in the signature. Slurpy parameters cannot
590 have default values: if no arguments are supplied for them then you get
591 an empty array or empty hash.
592 .PP
593 A signature may be entirely empty, in which case all it does is check
594 that the caller passed no arguments:
595 .PP
596 .Vb 3
597 \& sub foo () {
598 \& return 123;
599 \& }
600 .Ve
601 .PP
602 Prior to Perl 5.36 these were considered experimental, and emitted a
603 warning in the \f(CW\*(C`experimental::signatures\*(C'\fR category. From Perl 5.36
604 onwards this no longer happens, though the warning category still exists
605 for back-compatibility with code that attempts to disable it with a
606 statement such as:
607 .PP
608 .Vb 1
609 \& no warnings \*(Aqexperimental::signatures\*(Aq;
610 .Ve
611 .PP
612 In the current Perl implementation, when using a signature the arguments
613 are still also available in the special array variable \f(CW@_\fR. However,
614 accessing them via this array is now discouraged, and should not be
615 relied upon in newly-written code as this ability may change in a future
616 version. Code that attempts to access the \f(CW@_\fR array will produce
617 warnings in the \f(CW\*(C`experimental::args_array_with_signatures\*(C'\fR category when
618 compiled:
619 .PP
620 .Vb 4
621 \& sub f ($x) {
622 \& # This line emits the warning seen below
623 \& print "Arguments are @_";
624 \& }
625 .Ve
626 .PP
627
628 .PP
629 .Vb 2
630 \& Use of @_ in join or string with signatured subroutine is
631 \& experimental at ...
632 .Ve
633 .PP
634 There is a difference between the two ways of accessing the arguments:
635 \&\f(CW@_\fR \fIaliases\fR the arguments, but the signature variables get
636 \&\fIcopies\fR of the arguments. So writing to a signature variable only
637 changes that variable, and has no effect on the caller's variables, but
638 writing to an element of \f(CW@_\fR modifies whatever the caller used to
639 supply that argument.
640 .PP
641 There is a potential syntactic ambiguity between signatures and prototypes
642 (see "Prototypes"), because both start with an opening parenthesis and
643 both can appear in some of the same places, such as just after the name
644 in a subroutine declaration. For historical reasons, when signatures
645 are not enabled, any opening parenthesis in such a context will trigger
646 very forgiving prototype parsing. Most signatures will be interpreted
647 as prototypes in those circumstances, but won't be valid prototypes.
648 (A valid prototype cannot contain any alphabetic character.) This will
649 lead to somewhat confusing error messages.
650 .PP
651 To avoid ambiguity, when signatures are enabled the special syntax
652 for prototypes is disabled. There is no attempt to guess whether a
653 parenthesised group was intended to be a prototype or a signature.
654 To give a subroutine a prototype under these circumstances, use a
655 prototype attribute. For example,
656 .PP
657 .Vb 1
658 \& sub foo :prototype($) { $_[0] }
659 .Ve
660 .PP
661 It is entirely possible for a subroutine to have both a prototype and
662 a signature. They do different jobs: the prototype affects compilation
663 of calls to the subroutine, and the signature puts argument values into
664 lexical variables at runtime. You can therefore write
665 .PP
666 .Vb 3
667 \& sub foo :prototype($$) ($left, $right) {
668 \& return $left + $right;
669 \& }
670 .Ve
671 .PP
672 The prototype attribute, and any other attributes, must come before
673 the signature. The signature always immediately precedes the block of
674 the subroutine's body.
675 .SS "Private Variables via \fBmy()\fP"
676 .IX Xref "my variable, lexical lexical lexical variable scope, lexical lexical scope attributes, my"
677 .IX Subsection "Private Variables via my()"
678 Synopsis:
679 .PP
680 .Vb 5
681 \& my $foo; # declare $foo lexically local
682 \& my (@wid, %get); # declare list of variables local
683 \& my $foo = "flurp"; # declare $foo lexical, and init it
684 \& my @oof = @bar; # declare @oof lexical, and init it
685 \& my $x : Foo = $y; # similar, with an attribute applied
686 .Ve
687 .PP
688 \&\fBWARNING\fR: The use of attribute lists on \f(CW\*(C`my\*(C'\fR declarations is still
689 evolving. The current semantics and interface are subject to change.
690 See attributes and Attribute::Handlers.
691 .PP
692 The \f(CW\*(C`my\*(C'\fR operator declares the listed variables to be lexically
693 confined to the enclosing block, conditional
694 (\f(CW\*(C`if\*(C'\fR/\f(CW\*(C`unless\*(C'\fR/\f(CW\*(C`elsif\*(C'\fR/\f(CW\*(C`else\*(C'\fR), loop
695 (\f(CW\*(C`for\*(C'\fR/\f(CW\*(C`foreach\*(C'\fR/\f(CW\*(C`while\*(C'\fR/\f(CW\*(C`until\*(C'\fR/\f(CW\*(C`continue\*(C'\fR), subroutine, \f(CW\*(C`eval\*(C'\fR,
696 or \f(CW\*(C`do\*(C'\fR/\f(CW\*(C`require\*(C'\fR/\f(CW\*(C`use\*(C'\fR'd file. If more than one value is listed, the
697 list must be placed in parentheses. All listed elements must be
698 legal lvalues. Only alphanumeric identifiers may be lexically
699 scoped\-\-magical built-ins like \f(CW$/\fR must currently be \f(CW\*(C`local\*(C'\fRized
700 with \f(CW\*(C`local\*(C'\fR instead to limit their scope dynamically.
701 .PP
702 Unlike global or package variables localized by the \f(CW\*(C`local\*(C'\fR operator,
703 lexical variables declared with \f(CW\*(C`my\*(C'\fR are totally hidden from the outside
704 world, including any called subroutines. This is true if it's the same
705 subroutine called from itself or elsewhere\-\-every call gets its own copy.
706 .IX Xref "local"
707 .PP
708 This doesn't mean that a \f(CW\*(C`my\*(C'\fR variable declared in a statically
709 enclosing lexical scope would be invisible. Only dynamic scopes
710 are cut off. For example, the \f(CWbumpx()\fR function below has access
711 to the lexical \f(CW$x\fR variable because both the \f(CW\*(C`my\*(C'\fR and the \f(CW\*(C`sub\*(C'\fR
712 occurred at the same scope, presumably file scope.
713 .PP
714 .Vb 2
715 \& my $x = 10;
716 \& sub bumpx { $x++ }
717 .Ve
718 .PP
719 An \f(CWeval()\fR, however, can see lexical variables of the scope it is
720 being evaluated in, so long as the names aren't hidden by declarations within
721 the \f(CWeval()\fR itself. See perlref.
722 .IX Xref "eval, scope of"
723 .PP
724 The parameter list to \fBmy()\fR may be assigned to if desired, which allows you
725 to initialize your variables. (If no initializer is given for a
726 particular variable, it is created with the undefined value.) Commonly
727 this is used to name input parameters to a subroutine. Examples:
728 .PP
729 .Vb 4
730 \& $arg = "fred"; # "global" variable
731 \& $n = cube_root(27);
732 \& print "$arg thinks the root is $n\en";
733 \& # outputs: fred thinks the root is 3
734 \&
735 \& sub cube_root {
736 \& my $arg = shift; # name doesn\*(Aqt matter
737 \& $arg **= 1/3;
738 \& return $arg;
739 \& }
740 .Ve
741 .PP
742 The \f(CW\*(C`my\*(C'\fR is simply a modifier on something you might assign to. So when
743 you do assign to variables in its argument list, \f(CW\*(C`my\*(C'\fR doesn't
744 change whether those variables are viewed as a scalar or an array. So
745 .PP
746 .Vb 2
747 \& my ($foo) = <STDIN>; # WRONG?
748 \& my @FOO = <STDIN>;
749 .Ve
750 .PP
751 both supply a list context to the right-hand side, while
752 .PP
753 .Vb 1
754 \& my $foo = <STDIN>;
755 .Ve
756 .PP
757 supplies a scalar context. But the following declares only one variable:
758 .PP
759 .Vb 1
760 \& my $foo, $bar = 1; # WRONG
761 .Ve
762 .PP
763 That has the same effect as
764 .PP
765 .Vb 2
766 \& my $foo;
767 \& $bar = 1;
768 .Ve
769 .PP
770 The declared variable is not introduced (is not visible) until after
771 the current statement. Thus,
772 .PP
773 .Vb 1
774 \& my $x = $x;
775 .Ve
776 .PP
777 can be used to initialize a new \f(CW$x\fR with the value of the old \f(CW$x\fR, and
778 the expression
779 .PP
780 .Vb 1
781 \& my $x = 123 and $x == 123
782 .Ve
783 .PP
784 is false unless the old \f(CW$x\fR happened to have the value \f(CW123\fR.
785 .PP
786 Lexical scopes of control structures are not bounded precisely by the
787 braces that delimit their controlled blocks; control expressions are
788 part of that scope, too. Thus in the loop
789 .PP
790 .Vb 5
791 \& while (my $line = <>) {
792 \& $line = lc $line;
793 \& } continue {
794 \& print $line;
795 \& }
796 .Ve
797 .PP
798 the scope of \f(CW$line\fR extends from its declaration throughout the rest of
799 the loop construct (including the \f(CW\*(C`continue\*(C'\fR clause), but not beyond
800 it. Similarly, in the conditional
801 .PP
802 .Vb 8
803 \& if ((my $answer = <STDIN>) =~ /^yes$/i) {
804 \& user_agrees();
805 \& } elsif ($answer =~ /^no$/i) {
806 \& user_disagrees();
807 \& } else {
808 \& chomp $answer;
809 \& die "\*(Aq$answer\*(Aq is neither \*(Aqyes\*(Aq nor \*(Aqno\*(Aq";
810 \& }
811 .Ve
812 .PP
813 the scope of \f(CW$answer\fR extends from its declaration through the rest
814 of that conditional, including any \f(CW\*(C`elsif\*(C'\fR and \f(CW\*(C`else\*(C'\fR clauses,
815 but not beyond it. See "Simple Statements" in perlsyn for information
816 on the scope of variables in statements with modifiers.
817 .PP
818 The \f(CW\*(C`foreach\*(C'\fR loop defaults to scoping its index variable dynamically
819 in the manner of \f(CW\*(C`local\*(C'\fR. However, if the index variable is
820 prefixed with the keyword \f(CW\*(C`my\*(C'\fR, or if there is already a lexical
821 by that name in scope, then a new lexical is created instead. Thus
822 in the loop
823 .IX Xref "foreach for"
824 .PP
825 .Vb 3
826 \& for my $i (1, 2, 3) {
827 \& some_function();
828 \& }
829 .Ve
830 .PP
831 the scope of \f(CW$i\fR extends to the end of the loop, but not beyond it,
832 rendering the value of \f(CW$i\fR inaccessible within \f(CWsome_function()\fR.
833 .IX Xref "foreach for"
834 .PP
835 Some users may wish to encourage the use of lexically scoped variables.
836 As an aid to catching implicit uses to package variables,
837 which are always global, if you say
838 .PP
839 .Vb 1
840 \& use strict \*(Aqvars\*(Aq;
841 .Ve
842 .PP
843 then any variable mentioned from there to the end of the enclosing
844 block must either refer to a lexical variable, be predeclared via
845 \&\f(CW\*(C`our\*(C'\fR or \f(CW\*(C`use vars\*(C'\fR, or else must be fully qualified with the package name.
846 A compilation error results otherwise. An inner block may countermand
847 this with \f(CW\*(C`no strict \*(Aqvars\*(Aq\*(C'\fR.
848 .PP
849 A \f(CW\*(C`my\*(C'\fR has both a compile-time and a run-time effect. At compile
850 time, the compiler takes notice of it. The principal usefulness
851 of this is to quiet \f(CW\*(C`use strict \*(Aqvars\*(Aq\*(C'\fR, but it is also essential
852 for generation of closures as detailed in perlref. Actual
853 initialization is delayed until run time, though, so it gets executed
854 at the appropriate time, such as each time through a loop, for
855 example.
856 .PP
857 Variables declared with \f(CW\*(C`my\*(C'\fR are not part of any package and are therefore
858 never fully qualified with the package name. In particular, you're not
859 allowed to try to make a package variable (or other global) lexical:
860 .PP
861 .Vb 1
862 \& my $pack::var; # ERROR! Illegal syntax
863 .Ve
864 .PP
865 In fact, a package or global variable is still accessible using the
866 fully qualified \f(CW\*(C`::\*(C'\fR notation even while a lexical of the same name
867 is also visible:
868 .PP
869 .Vb 4
870 \& package main;
871 \& our $x = 10;
872 \& my $x = 20;
873 \& print "$x and $::x\en";
874 .Ve
875 .PP
876 That will print out \f(CW20\fR and \f(CW10\fR.
877 .PP
878 You may declare \f(CW\*(C`my\*(C'\fR variables at the outermost scope of a file
879 to hide any such identifiers from the world outside that file. This
880 is similar in spirit to C's static variables when they are used at
881 the file level. To do this with a subroutine requires the use of
882 a closure (an anonymous function that accesses enclosing lexicals).
883 If you want to create a private subroutine that cannot be called
884 from outside that block, it can declare a lexical variable containing
885 an anonymous sub reference:
886 .PP
887 .Vb 3
888 \& my $secret_version = \*(Aq1.001\-beta\*(Aq;
889 \& my $secret_sub = sub { print $secret_version };
890 \& $secret_sub\->();
891 .Ve
892 .PP
893 As long as the reference is never returned by any function within the
894 module, no outside module can see the subroutine, because its name is not in
895 any package's symbol table. Remember that it's not \fIREALLY\fR called
896 \&\f(CW$some_pack::secret_version\fR or anything; it's just \f(CW$secret_version\fR,
897 unqualified and unqualifiable.
898 .PP
899 This does not work with object methods, however; all object methods
900 have to be in the symbol table of some package to be found. See
901 "Function Templates" in perlref for something of a work-around to
902 this.
903 .SS "Persistent Private Variables"
904 .IX Xref "state state variable static variable, persistent variable, static closure"
905 .IX Subsection "Persistent Private Variables"
906 There are two ways to build persistent private variables in Perl 5.10.
907 First, you can simply use the \f(CW\*(C`state\*(C'\fR feature. Or, you can use closures,
908 if you want to stay compatible with releases older than 5.10.
909 .PP
910 \fIPersistent variables via \fR\f(BIstate()\fR
911 .IX Subsection "Persistent variables via state()"
912 .PP
913 Beginning with Perl 5.10.0, you can declare variables with the \f(CW\*(C`state\*(C'\fR
914 keyword in place of \f(CW\*(C`my\*(C'\fR. For that to work, though, you must have
915 enabled that feature beforehand, either by using the \f(CW\*(C`feature\*(C'\fR pragma, or
916 by using \f(CW\*(C`\-E\*(C'\fR on one-liners (see feature). Beginning with Perl 5.16,
917 the \f(CW\*(C`CORE::state\*(C'\fR form does not require the
918 \&\f(CW\*(C`feature\*(C'\fR pragma.
919 .PP
920 The \f(CW\*(C`state\*(C'\fR keyword creates a lexical variable (following the same scoping
921 rules as \f(CW\*(C`my\*(C'\fR) that persists from one subroutine call to the next. If a
922 state variable resides inside an anonymous subroutine, then each copy of
923 the subroutine has its own copy of the state variable. However, the value
924 of the state variable will still persist between calls to the same copy of
925 the anonymous subroutine. (Don't forget that \f(CW\*(C`sub { ... }\*(C'\fR creates a new
926 subroutine each time it is executed.)
927 .PP
928 For example, the following code maintains a private counter, incremented
929 each time the \fBgimme_another()\fR function is called:
930 .PP
931 .Vb 2
932 \& use feature \*(Aqstate\*(Aq;
933 \& sub gimme_another { state $x; return ++$x }
934 .Ve
935 .PP
936 And this example uses anonymous subroutines to create separate counters:
937 .PP
938 .Vb 4
939 \& use feature \*(Aqstate\*(Aq;
940 \& sub create_counter {
941 \& return sub { state $x; return ++$x }
942 \& }
943 .Ve
944 .PP
945 Also, since \f(CW$x\fR is lexical, it can't be reached or modified by any Perl
946 code outside.
947 .PP
948 When combined with variable declaration, simple assignment to \f(CW\*(C`state\*(C'\fR
949 variables (as in \f(CW\*(C`state $x = 42\*(C'\fR) is executed only the first time. When such
950 statements are evaluated subsequent times, the assignment is ignored. The
951 behavior of assignment to \f(CW\*(C`state\*(C'\fR declarations where the left hand side
952 of the assignment involves any parentheses is currently undefined.
953 .PP
954 \fIPersistent variables with closures\fR
955 .IX Subsection "Persistent variables with closures"
956 .PP
957 Just because a lexical variable is lexically (also called statically)
958 scoped to its enclosing block, \f(CW\*(C`eval\*(C'\fR, or \f(CW\*(C`do\*(C'\fR FILE, this doesn't mean that
959 within a function it works like a C static. It normally works more
960 like a C auto, but with implicit garbage collection.
961 .PP
962 Unlike local variables in C or C++, Perl's lexical variables don't
963 necessarily get recycled just because their scope has exited.
964 If something more permanent is still aware of the lexical, it will
965 stick around. So long as something else references a lexical, that
966 lexical won't be freed\-\-which is as it should be. You wouldn't want
967 memory being free until you were done using it, or kept around once you
968 were done. Automatic garbage collection takes care of this for you.
969 .PP
970 This means that you can pass back or save away references to lexical
971 variables, whereas to return a pointer to a C auto is a grave error.
972 It also gives us a way to simulate C's function statics. Here's a
973 mechanism for giving a function private variables with both lexical
974 scoping and a static lifetime. If you do want to create something like
975 C's static variables, just enclose the whole function in an extra block,
976 and put the static variable outside the function but in the block.
977 .PP
978 .Vb 8
979 \& {
980 \& my $secret_val = 0;
981 \& sub gimme_another {
982 \& return ++$secret_val;
983 \& }
984 \& }
985 \& # $secret_val now becomes unreachable by the outside
986 \& # world, but retains its value between calls to gimme_another
987 .Ve
988 .PP
989 If this function is being sourced in from a separate file
990 via \f(CW\*(C`require\*(C'\fR or \f(CW\*(C`use\*(C'\fR, then this is probably just fine. If it's
991 all in the main program, you'll need to arrange for the \f(CW\*(C`my\*(C'\fR
992 to be executed early, either by putting the whole block above
993 your main program, or more likely, placing merely a \f(CW\*(C`BEGIN\*(C'\fR
994 code block around it to make sure it gets executed before your program
995 starts to run:
996 .PP
997 .Vb 6
998 \& BEGIN {
999 \& my $secret_val = 0;
1000 \& sub gimme_another {
1001 \& return ++$secret_val;
1002 \& }
1003 \& }
1004 .Ve
1005 .PP
1006 See "BEGIN, UNITCHECK, CHECK, INIT and END" in perlmod about the
1007 special triggered code blocks, \f(CW\*(C`BEGIN\*(C'\fR, \f(CW\*(C`UNITCHECK\*(C'\fR, \f(CW\*(C`CHECK\*(C'\fR,
1008 \&\f(CW\*(C`INIT\*(C'\fR and \f(CW\*(C`END\*(C'\fR.
1009 .PP
1010 If declared at the outermost scope (the file scope), then lexicals
1011 work somewhat like C's file statics. They are available to all
1012 functions in that same file declared below them, but are inaccessible
1013 from outside that file. This strategy is sometimes used in modules
1014 to create private variables that the whole module can see.
1015 .SS "Temporary Values via \fBlocal()\fP"
1016 .IX Xref "local scope, dynamic dynamic scope variable, local variable, temporary"
1017 .IX Subsection "Temporary Values via local()"
1018 \&\fBWARNING\fR: In general, you should be using \f(CW\*(C`my\*(C'\fR instead of \f(CW\*(C`local\*(C'\fR, because
1019 it's faster and safer. Exceptions to this include the global punctuation
1020 variables, global filehandles and formats, and direct manipulation of the
1021 Perl symbol table itself. \f(CW\*(C`local\*(C'\fR is mostly used when the current value
1022 of a variable must be visible to called subroutines.
1023 .PP
1024 Synopsis:
1025 .PP
1026 .Vb 1
1027 \& # localization of values
1028 \&
1029 \& local $foo; # make $foo dynamically local
1030 \& local (@wid, %get); # make list of variables local
1031 \& local $foo = "flurp"; # make $foo dynamic, and init it
1032 \& local @oof = @bar; # make @oof dynamic, and init it
1033 \&
1034 \& local $hash{key} = "val"; # sets a local value for this hash entry
1035 \& delete local $hash{key}; # delete this entry for the current block
1036 \& local ($cond ? $v1 : $v2); # several types of lvalues support
1037 \& # localization
1038 \&
1039 \& # localization of symbols
1040 \&
1041 \& local *FH; # localize $FH, @FH, %FH, &FH ...
1042 \& local *merlyn = *randal; # now $merlyn is really $randal, plus
1043 \& # @merlyn is really @randal, etc
1044 \& local *merlyn = \*(Aqrandal\*(Aq; # SAME THING: promote \*(Aqrandal\*(Aq to *randal
1045 \& local *merlyn = \e$randal; # just alias $merlyn, not @merlyn etc
1046 .Ve
1047 .PP
1048 A \f(CW\*(C`local\*(C'\fR modifies its listed variables to be "local" to the
1049 enclosing block, \f(CW\*(C`eval\*(C'\fR, or \f(CW\*(C`do FILE\*(C'\fR\-\-and to \fIany subroutine
1050 called from within that block\fR. A \f(CW\*(C`local\*(C'\fR just gives temporary
1051 values to global (meaning package) variables. It does \fInot\fR create
1052 a local variable. This is known as dynamic scoping. Lexical scoping
1053 is done with \f(CW\*(C`my\*(C'\fR, which works more like C's auto declarations.
1054 .PP
1055 Some types of lvalues can be localized as well: hash and array elements
1056 and slices, conditionals (provided that their result is always
1057 localizable), and symbolic references. As for simple variables, this
1058 creates new, dynamically scoped values.
1059 .PP
1060 If more than one variable or expression is given to \f(CW\*(C`local\*(C'\fR, they must be
1061 placed in parentheses. This operator works
1062 by saving the current values of those variables in its argument list on a
1063 hidden stack and restoring them upon exiting the block, subroutine, or
1064 eval. This means that called subroutines can also reference the local
1065 variable, but not the global one. The argument list may be assigned to if
1066 desired, which allows you to initialize your local variables. (If no
1067 initializer is given for a particular variable, it is created with an
1068 undefined value.)
1069 .PP
1070 Because \f(CW\*(C`local\*(C'\fR is a run-time operator, it gets executed each time
1071 through a loop. Consequently, it's more efficient to localize your
1072 variables outside the loop.
1073 .PP
1074 \fIGrammatical note on \fR\f(BIlocal()\fR
1075 .IX Xref "local, context"
1076 .IX Subsection "Grammatical note on local()"
1077 .PP
1078 A \f(CW\*(C`local\*(C'\fR is simply a modifier on an lvalue expression. When you assign to
1079 a \f(CW\*(C`local\*(C'\fRized variable, the \f(CW\*(C`local\*(C'\fR doesn't change whether its list is
1080 viewed as a scalar or an array. So
1081 .PP
1082 .Vb 2
1083 \& local($foo) = <STDIN>;
1084 \& local @FOO = <STDIN>;
1085 .Ve
1086 .PP
1087 both supply a list context to the right-hand side, while
1088 .PP
1089 .Vb 1
1090 \& local $foo = <STDIN>;
1091 .Ve
1092 .PP
1093 supplies a scalar context.
1094 .PP
1095 \fILocalization of special variables\fR
1096 .IX Xref "local, special variable"
1097 .IX Subsection "Localization of special variables"
1098 .PP
1099 If you localize a special variable, you'll be giving a new value to it,
1100 but its magic won't go away. That means that all side-effects related
1101 to this magic still work with the localized value.
1102 .PP
1103 This feature allows code like this to work :
1104 .PP
1105 .Vb 2
1106 \& # Read the whole contents of FILE in $slurp
1107 \& { local $/ = undef; $slurp = <FILE>; }
1108 .Ve
1109 .PP
1110 Note, however, that this restricts localization of some values ; for
1111 example, the following statement dies, as of Perl 5.10.0, with an error
1112 \&\fIModification of a read-only value attempted\fR, because the \f(CW$1\fR variable is
1113 magical and read-only :
1114 .PP
1115 .Vb 1
1116 \& local $1 = 2;
1117 .Ve
1118 .PP
1119 One exception is the default scalar variable: starting with Perl 5.14
1120 \&\f(CWlocal($_)\fR will always strip all magic from \f(CW$_\fR, to make it possible
1121 to safely reuse \f(CW$_\fR in a subroutine.
1122 .PP
1123 \&\fBWARNING\fR: Localization of tied arrays and hashes does not currently
1124 work as described.
1125 This will be fixed in a future release of Perl; in the meantime, avoid
1126 code that relies on any particular behavior of localising tied arrays
1127 or hashes (localising individual elements is still okay).
1128 See "Localising Tied Arrays and Hashes Is Broken" in perl58delta for more
1129 details.
1130 .IX Xref "local, tie"
1131 .PP
1132 \fILocalization of globs\fR
1133 .IX Xref "local, glob glob"
1134 .IX Subsection "Localization of globs"
1135 .PP
1136 The construct
1137 .PP
1138 .Vb 1
1139 \& local *name;
1140 .Ve
1141 .PP
1142 creates a whole new symbol table entry for the glob \f(CW\*(C`name\*(C'\fR in the
1143 current package. That means that all variables in its glob slot ($name,
1144 \&\f(CW@name\fR, \f(CW%name\fR, &name, and the \f(CW\*(C`name\*(C'\fR filehandle) are dynamically reset.
1145 .PP
1146 This implies, among other things, that any magic eventually carried by
1147 those variables is locally lost. In other words, saying \f(CW\*(C`local */\*(C'\fR
1148 will not have any effect on the internal value of the input record
1149 separator.
1150 .PP
1151 \fILocalization of elements of composite types\fR
1152 .IX Xref "local, composite type element local, array element local, hash element"
1153 .IX Subsection "Localization of elements of composite types"
1154 .PP
1155 It's also worth taking a moment to explain what happens when you
1156 \&\f(CW\*(C`local\*(C'\fRize a member of a composite type (i.e. an array or hash element).
1157 In this case, the element is \f(CW\*(C`local\*(C'\fRized \fIby name\fR. This means that
1158 when the scope of the \f(CWlocal()\fR ends, the saved value will be
1159 restored to the hash element whose key was named in the \f(CWlocal()\fR, or
1160 the array element whose index was named in the \f(CWlocal()\fR. If that
1161 element was deleted while the \f(CWlocal()\fR was in effect (e.g. by a
1162 \&\f(CWdelete()\fR from a hash or a \f(CWshift()\fR of an array), it will spring
1163 back into existence, possibly extending an array and filling in the
1164 skipped elements with \f(CW\*(C`undef\*(C'\fR. For instance, if you say
1165 .PP
1166 .Vb 10
1167 \& %hash = ( \*(AqThis\*(Aq => \*(Aqis\*(Aq, \*(Aqa\*(Aq => \*(Aqtest\*(Aq );
1168 \& @ary = ( 0..5 );
1169 \& {
1170 \& local($ary[5]) = 6;
1171 \& local($hash{\*(Aqa\*(Aq}) = \*(Aqdrill\*(Aq;
1172 \& while (my $e = pop(@ary)) {
1173 \& print "$e . . .\en";
1174 \& last unless $e > 3;
1175 \& }
1176 \& if (@ary) {
1177 \& $hash{\*(Aqonly a\*(Aq} = \*(Aqtest\*(Aq;
1178 \& delete $hash{\*(Aqa\*(Aq};
1179 \& }
1180 \& }
1181 \& print join(\*(Aq \*(Aq, map { "$_ $hash{$_}" } sort keys %hash),".\en";
1182 \& print "The array has ",scalar(@ary)," elements: ",
1183 \& join(\*(Aq, \*(Aq, map { defined $_ ? $_ : \*(Aqundef\*(Aq } @ary),"\en";
1184 .Ve
1185 .PP
1186 Perl will print
1187 .PP
1188 .Vb 5
1189 \& 6 . . .
1190 \& 4 . . .
1191 \& 3 . . .
1192 \& This is a test only a test.
1193 \& The array has 6 elements: 0, 1, 2, undef, undef, 5
1194 .Ve
1195 .PP
1196 The behavior of \fBlocal()\fR on non-existent members of composite
1197 types is subject to change in future. The behavior of \fBlocal()\fR
1198 on array elements specified using negative indexes is particularly
1199 surprising, and is very likely to change.
1200 .PP
1201 \fILocalized deletion of elements of composite types\fR
1202 .IX Xref "delete local, composite type element local, array element local, hash element"
1203 .IX Subsection "Localized deletion of elements of composite types"
1204 .PP
1205 You can use the \f(CW\*(C`delete local $array[$idx]\*(C'\fR and \f(CW\*(C`delete local $hash{key}\*(C'\fR
1206 constructs to delete a composite type entry for the current block and restore
1207 it when it ends. They return the array/hash value before the localization,
1208 which means that they are respectively equivalent to
1209 .PP
1210 .Vb 6
1211 \& do {
1212 \& my $val = $array[$idx];
1213 \& local $array[$idx];
1214 \& delete $array[$idx];
1215 \& $val
1216 \& }
1217 .Ve
1218 .PP
1219 and
1220 .PP
1221 .Vb 6
1222 \& do {
1223 \& my $val = $hash{key};
1224 \& local $hash{key};
1225 \& delete $hash{key};
1226 \& $val
1227 \& }
1228 .Ve
1229 .PP
1230 except that for those the \f(CW\*(C`local\*(C'\fR is
1231 scoped to the \f(CW\*(C`do\*(C'\fR block. Slices are
1232 also accepted.
1233 .PP
1234 .Vb 4
1235 \& my %hash = (
1236 \& a => [ 7, 8, 9 ],
1237 \& b => 1,
1238 \& )
1239 \&
1240 \& {
1241 \& my $x = delete local $hash{a};
1242 \& # $x is [ 7, 8, 9 ]
1243 \& # %hash is (b => 1)
1244 \&
1245 \& {
1246 \& my @nums = delete local @$x[0, 2]
1247 \& # @nums is (7, 9)
1248 \& # $x is [ undef, 8 ]
1249 \&
1250 \& $x[0] = 999; # will be erased when the scope ends
1251 \& }
1252 \& # $x is back to [ 7, 8, 9 ]
1253 \&
1254 \& }
1255 \& # %hash is back to its original state
1256 .Ve
1257 .PP
1258 This construct is supported since Perl v5.12.
1259 .SS "Lvalue subroutines"
1260 .IX Xref "lvalue subroutine, lvalue"
1261 .IX Subsection "Lvalue subroutines"
1262 It is possible to return a modifiable value from a subroutine.
1263 To do this, you have to declare the subroutine to return an lvalue.
1264 .PP
1265 .Vb 7
1266 \& my $val;
1267 \& sub canmod : lvalue {
1268 \& $val; # or: return $val;
1269 \& }
1270 \& sub nomod {
1271 \& $val;
1272 \& }
1273 \&
1274 \& canmod() = 5; # assigns to $val
1275 \& nomod() = 5; # ERROR
1276 .Ve
1277 .PP
1278 The scalar/list context for the subroutine and for the right-hand
1279 side of assignment is determined as if the subroutine call is replaced
1280 by a scalar. For example, consider:
1281 .PP
1282 .Vb 1
1283 \& data(2,3) = get_data(3,4);
1284 .Ve
1285 .PP
1286 Both subroutines here are called in a scalar context, while in:
1287 .PP
1288 .Vb 1
1289 \& (data(2,3)) = get_data(3,4);
1290 .Ve
1291 .PP
1292 and in:
1293 .PP
1294 .Vb 1
1295 \& (data(2),data(3)) = get_data(3,4);
1296 .Ve
1297 .PP
1298 all the subroutines are called in a list context.
1299 .PP
1300 Lvalue subroutines are convenient, but you have to keep in mind that,
1301 when used with objects, they may violate encapsulation. A normal
1302 mutator can check the supplied argument before setting the attribute
1303 it is protecting, an lvalue subroutine cannot. If you require any
1304 special processing when storing and retrieving the values, consider
1305 using the CPAN module Sentinel or something similar.
1306 .SS "Lexical Subroutines"
1307 .IX Xref "my sub state sub our sub subroutine, lexical"
1308 .IX Subsection "Lexical Subroutines"
1309 Beginning with Perl 5.18, you can declare a private subroutine with \f(CW\*(C`my\*(C'\fR
1310 or \f(CW\*(C`state\*(C'\fR. As with state variables, the \f(CW\*(C`state\*(C'\fR keyword is only
1311 available under \f(CW\*(C`use feature \*(Aqstate\*(Aq\*(C'\fR or \f(CW\*(C`use v5.10\*(C'\fR or higher.
1312 .PP
1313 Prior to Perl 5.26, lexical subroutines were deemed experimental and were
1314 available only under the \f(CW\*(C`use feature \*(Aqlexical_subs\*(Aq\*(C'\fR pragma. They also
1315 produced a warning unless the "experimental::lexical_subs" warnings
1316 category was disabled.
1317 .PP
1318 These subroutines are only visible within the block in which they are
1319 declared, and only after that declaration:
1320 .PP
1321 .Vb 4
1322 \& # Include these two lines if your code is intended to run under Perl
1323 \& # versions earlier than 5.26.
1324 \& no warnings "experimental::lexical_subs";
1325 \& use feature \*(Aqlexical_subs\*(Aq;
1326 \&
1327 \& foo(); # calls the package/global subroutine
1328 \& state sub foo {
1329 \& foo(); # also calls the package subroutine
1330 \& }
1331 \& foo(); # calls "state" sub
1332 \& my $ref = \e&foo; # take a reference to "state" sub
1333 \&
1334 \& my sub bar { ... }
1335 \& bar(); # calls "my" sub
1336 .Ve
1337 .PP
1338 You can't (directly) write a recursive lexical subroutine:
1339 .PP
1340 .Vb 4
1341 \& # WRONG
1342 \& my sub baz {
1343 \& baz();
1344 \& }
1345 .Ve
1346 .PP
1347 This example fails because \f(CWbaz()\fR refers to the package/global subroutine
1348 \&\f(CW\*(C`baz\*(C'\fR, not the lexical subroutine currently being defined.
1349 .PP
1350 The solution is to use \f(CW\*(C`_\|_SUB_\|_\*(C'\fR:
1351 .PP
1352 .Vb 3
1353 \& my sub baz {
1354 \& _\|_SUB_\|_\->(); # calls itself
1355 \& }
1356 .Ve
1357 .PP
1358 It is possible to predeclare a lexical subroutine. The \f(CW\*(C`sub foo {...}\*(C'\fR
1359 subroutine definition syntax respects any previous \f(CW\*(C`my sub;\*(C'\fR or \f(CW\*(C`state sub;\*(C'\fR
1360 declaration. Using this to define recursive subroutines is a bad idea,
1361 however:
1362 .PP
1363 .Vb 4
1364 \& my sub baz; # predeclaration
1365 \& sub baz { # define the "my" sub
1366 \& baz(); # WRONG: calls itself, but leaks memory
1367 \& }
1368 .Ve
1369 .PP
1370 Just like \f(CW\*(C`my $f; $f = sub { $f\->() }\*(C'\fR, this example leaks memory. The
1371 name \f(CW\*(C`baz\*(C'\fR is a reference to the subroutine, and the subroutine uses the name
1372 \&\f(CW\*(C`baz\*(C'\fR; they keep each other alive (see "Circular References" in perlref).
1373 .PP
1374 \fR\f(CI\*(C`state sub\*(C'\fR\fI vs \fR\f(CI\*(C`my sub\*(C'\fR\fI\fR
1375 .IX Subsection "state sub vs my sub"
1376 .PP
1377 What is the difference between "state" subs and "my" subs? Each time that
1378 execution enters a block when "my" subs are declared, a new copy of each
1379 sub is created. "State" subroutines persist from one execution of the
1380 containing block to the next.
1381 .PP
1382 So, in general, "state" subroutines are faster. But "my" subs are
1383 necessary if you want to create closures:
1384 .PP
1385 .Vb 7
1386 \& sub whatever {
1387 \& my $x = shift;
1388 \& my sub inner {
1389 \& ... do something with $x ...
1390 \& }
1391 \& inner();
1392 \& }
1393 .Ve
1394 .PP
1395 In this example, a new \f(CW$x\fR is created when \f(CW\*(C`whatever\*(C'\fR is called, and
1396 also a new \f(CW\*(C`inner\*(C'\fR, which can see the new \f(CW$x\fR. A "state" sub will only
1397 see the \f(CW$x\fR from the first call to \f(CW\*(C`whatever\*(C'\fR.
1398 .PP
1399 \fR\f(CI\*(C`our\*(C'\fR\fI subroutines\fR
1400 .IX Subsection "our subroutines"
1401 .PP
1402 Like \f(CW\*(C`our $variable\*(C'\fR, \f(CW\*(C`our sub\*(C'\fR creates a lexical alias to the package
1403 subroutine of the same name.
1404 .PP
1405 The two main uses for this are to switch back to using the package sub
1406 inside an inner scope:
1407 .PP
1408 .Vb 1
1409 \& sub foo { ... }
1410 \&
1411 \& sub bar {
1412 \& my sub foo { ... }
1413 \& {
1414 \& # need to use the outer foo here
1415 \& our sub foo;
1416 \& foo();
1417 \& }
1418 \& }
1419 .Ve
1420 .PP
1421 and to make a subroutine visible to other packages in the same scope:
1422 .PP
1423 .Vb 1
1424 \& package MySneakyModule;
1425 \&
1426 \& our sub do_something { ... }
1427 \&
1428 \& sub do_something_with_caller {
1429 \& package DB;
1430 \& () = caller 1; # sets @DB::args
1431 \& do_something(@args); # uses MySneakyModule::do_something
1432 \& }
1433 .Ve
1434 .SS "Passing Symbol Table Entries (typeglobs)"
1435 .IX Xref "typeglob *"
1436 .IX Subsection "Passing Symbol Table Entries (typeglobs)"
1437 \&\fBWARNING\fR: The mechanism described in this section was originally
1438 the only way to simulate pass-by-reference in older versions of
1439 Perl. While it still works fine in modern versions, the new reference
1440 mechanism is generally easier to work with. See below.
1441 .PP
1442 Sometimes you don't want to pass the value of an array to a subroutine
1443 but rather the name of it, so that the subroutine can modify the global
1444 copy of it rather than working with a local copy. In Perl you can
1445 refer to all objects of a particular name by prefixing the name
1446 with a star: \f(CW*foo\fR. This is often known as a "typeglob", because the
1447 star on the front can be thought of as a wildcard match for all the
1448 funny prefix characters on variables and subroutines and such.
1449 .PP
1450 When evaluated, the typeglob produces a scalar value that represents
1451 all the objects of that name, including any filehandle, format, or
1452 subroutine. When assigned to, it causes the name mentioned to refer to
1453 whatever \f(CW\*(C`*\*(C'\fR value was assigned to it. Example:
1454 .PP
1455 .Vb 8
1456 \& sub doubleary {
1457 \& local(*someary) = @_;
1458 \& foreach $elem (@someary) {
1459 \& $elem *= 2;
1460 \& }
1461 \& }
1462 \& doubleary(*foo);
1463 \& doubleary(*bar);
1464 .Ve
1465 .PP
1466 Scalars are already passed by reference, so you can modify
1467 scalar arguments without using this mechanism by referring explicitly
1468 to \f(CW$_[0]\fR etc. You can modify all the elements of an array by passing
1469 all the elements as scalars, but you have to use the \f(CW\*(C`*\*(C'\fR mechanism (or
1470 the equivalent reference mechanism) to \f(CW\*(C`push\*(C'\fR, \f(CW\*(C`pop\*(C'\fR, or change the size of
1471 an array. It will certainly be faster to pass the typeglob (or reference).
1472 .PP
1473 Even if you don't want to modify an array, this mechanism is useful for
1474 passing multiple arrays in a single LIST, because normally the LIST
1475 mechanism will merge all the array values so that you can't extract out
1476 the individual arrays. For more on typeglobs, see
1477 "Typeglobs and Filehandles" in perldata.
1478 .SS "When to Still Use \fBlocal()\fP"
1479 .IX Xref "local variable, local"
1480 .IX Subsection "When to Still Use local()"
1481 Despite the existence of \f(CW\*(C`my\*(C'\fR, there are still three places where the
1482 \&\f(CW\*(C`local\*(C'\fR operator still shines. In fact, in these three places, you
1483 \&\fImust\fR use \f(CW\*(C`local\*(C'\fR instead of \f(CW\*(C`my\*(C'\fR.
1484 .IP 1. 4
1485 You need to give a global variable a temporary value, especially \f(CW$_\fR.
1486 .Sp
1487 The global variables, like \f(CW@ARGV\fR or the punctuation variables, must be
1488 \&\f(CW\*(C`local\*(C'\fRized with \f(CWlocal()\fR. This block reads in \fI/etc/motd\fR, and splits
1489 it up into chunks separated by lines of equal signs, which are placed
1490 in \f(CW@Fields\fR.
1491 .Sp
1492 .Vb 6
1493 \& {
1494 \& local @ARGV = ("/etc/motd");
1495 \& local $/ = undef;
1496 \& local $_ = <>;
1497 \& @Fields = split /^\es*=+\es*$/;
1498 \& }
1499 .Ve
1500 .Sp
1501 It particular, it's important to \f(CW\*(C`local\*(C'\fRize \f(CW$_\fR in any routine that assigns
1502 to it. Look out for implicit assignments in \f(CW\*(C`while\*(C'\fR conditionals.
1503 .IP 2. 4
1504 You need to create a local file or directory handle or a local function.
1505 .Sp
1506 A function that needs a filehandle of its own must use
1507 \&\f(CWlocal()\fR on a complete typeglob. This can be used to create new symbol
1508 table entries:
1509 .Sp
1510 .Vb 6
1511 \& sub ioqueue {
1512 \& local (*READER, *WRITER); # not my!
1513 \& pipe (READER, WRITER) or die "pipe: $!";
1514 \& return (*READER, *WRITER);
1515 \& }
1516 \& ($head, $tail) = ioqueue();
1517 .Ve
1518 .Sp
1519 See the Symbol module for a way to create anonymous symbol table
1520 entries.
1521 .Sp
1522 Because assignment of a reference to a typeglob creates an alias, this
1523 can be used to create what is effectively a local function, or at least,
1524 a local alias.
1525 .Sp
1526 .Vb 6
1527 \& {
1528 \& local *grow = \e&shrink; # only until this block exits
1529 \& grow(); # really calls shrink()
1530 \& move(); # if move() grow()s, it shrink()s too
1531 \& }
1532 \& grow(); # get the real grow() again
1533 .Ve
1534 .Sp
1535 See "Function Templates" in perlref for more about manipulating
1536 functions by name in this way.
1537 .IP 3. 4
1538 You want to temporarily change just one element of an array or hash.
1539 .Sp
1540 You can \f(CW\*(C`local\*(C'\fRize just one element of an aggregate. Usually this
1541 is done on dynamics:
1542 .Sp
1543 .Vb 5
1544 \& {
1545 \& local $SIG{INT} = \*(AqIGNORE\*(Aq;
1546 \& funct(); # uninterruptible
1547 \& }
1548 \& # interruptibility automatically restored here
1549 .Ve
1550 .Sp
1551 But it also works on lexically declared aggregates.
1552 .SS "Pass by Reference"
1553 .IX Xref "pass by reference pass-by-reference reference"
1554 .IX Subsection "Pass by Reference"
1555 If you want to pass more than one array or hash into a function\-\-or
1556 return them from it\-\-and have them maintain their integrity, then
1557 you're going to have to use an explicit pass-by-reference. Before you
1558 do that, you need to understand references as detailed in perlref.
1559 This section may not make much sense to you otherwise.
1560 .PP
1561 Here are a few simple examples. First, let's pass in several arrays
1562 to a function and have it \f(CW\*(C`pop\*(C'\fR all of then, returning a new list
1563 of all their former last elements:
1564 .PP
1565 .Vb 1
1566 \& @tailings = popmany ( \e@w, \e@x, \e@y, \e@z );
1567 \&
1568 \& sub popmany {
1569 \& my $aref;
1570 \& my @retlist;
1571 \& foreach $aref ( @_ ) {
1572 \& push @retlist, pop @$aref;
1573 \& }
1574 \& return @retlist;
1575 \& }
1576 .Ve
1577 .PP
1578 Here's how you might write a function that returns a
1579 list of keys occurring in all the hashes passed to it:
1580 .PP
1581 .Vb 10
1582 \& @common = inter( \e%foo, \e%bar, \e%joe );
1583 \& sub inter {
1584 \& my ($k, $href, %seen); # locals
1585 \& foreach $href (@_) {
1586 \& while ( $k = each %$href ) {
1587 \& $seen{$k}++;
1588 \& }
1589 \& }
1590 \& return grep { $seen{$_} == @_ } keys %seen;
1591 \& }
1592 .Ve
1593 .PP
1594 So far, we're using just the normal list return mechanism.
1595 What happens if you want to pass or return a hash? Well,
1596 if you're using only one of them, or you don't mind them
1597 concatenating, then the normal calling convention is ok, although
1598 a little expensive.
1599 .PP
1600 Where people get into trouble is here:
1601 .PP
1602 .Vb 3
1603 \& (@w, @x) = func(@y, @z);
1604 \&or
1605 \& (%w, %x) = func(%y, %z);
1606 .Ve
1607 .PP
1608 That syntax simply won't work. It sets just \f(CW@w\fR or \f(CW%w\fR and
1609 clears the \f(CW@x\fR or \f(CW%x\fR. Plus the function didn't get passed
1610 into two separate arrays or hashes: it got one long list in \f(CW@_\fR,
1611 as always.
1612 .PP
1613 If you can arrange for everyone to deal with this through references, it's
1614 cleaner code, although not so nice to look at. Here's a function that
1615 takes two array references as arguments, returning the two array elements
1616 in order of how many elements they have in them:
1617 .PP
1618 .Vb 10
1619 \& ($wref, $xref) = func(\e@y, \e@z);
1620 \& print "@$wref has more than @$xref\en";
1621 \& sub func {
1622 \& my ($yref, $zref) = @_;
1623 \& if (@$yref > @$zref) {
1624 \& return ($yref, $zref);
1625 \& } else {
1626 \& return ($zref, $yref);
1627 \& }
1628 \& }
1629 .Ve
1630 .PP
1631 It turns out that you can actually do this also:
1632 .PP
1633 .Vb 10
1634 \& (*w, *x) = func(\e@y, \e@z);
1635 \& print "@w has more than @x\en";
1636 \& sub func {
1637 \& local (*y, *z) = @_;
1638 \& if (@y > @z) {
1639 \& return (\e@y, \e@z);
1640 \& } else {
1641 \& return (\e@z, \e@y);
1642 \& }
1643 \& }
1644 .Ve
1645 .PP
1646 Here we're using the typeglobs to do symbol table aliasing. It's
1647 a tad subtle, though, and also won't work if you're using \f(CW\*(C`my\*(C'\fR
1648 variables, because only globals (even in disguise as \f(CW\*(C`local\*(C'\fRs)
1649 are in the symbol table.
1650 .PP
1651 If you're passing around filehandles, you could usually just use the bare
1652 typeglob, like \f(CW*STDOUT\fR, but typeglobs references work, too.
1653 For example:
1654 .PP
1655 .Vb 5
1656 \& splutter(\e*STDOUT);
1657 \& sub splutter {
1658 \& my $fh = shift;
1659 \& print $fh "her um well a hmmm\en";
1660 \& }
1661 \&
1662 \& $rec = get_rec(\e*STDIN);
1663 \& sub get_rec {
1664 \& my $fh = shift;
1665 \& return scalar <$fh>;
1666 \& }
1667 .Ve
1668 .PP
1669 If you're planning on generating new filehandles, you could do this.
1670 Notice to pass back just the bare *FH, not its reference.
1671 .PP
1672 .Vb 5
1673 \& sub openit {
1674 \& my $path = shift;
1675 \& local *FH;
1676 \& return open (FH, $path) ? *FH : undef;
1677 \& }
1678 .Ve
1679 .SS Prototypes
1680 .IX Xref "prototype subroutine, prototype"
1681 .IX Subsection "Prototypes"
1682 Perl supports a very limited kind of compile-time argument checking
1683 using function prototyping. This can be declared in either the PROTO
1684 section or with a prototype attribute.
1685 If you declare either of
1686 .PP
1687 .Vb 2
1688 \& sub mypush (\e@@)
1689 \& sub mypush :prototype(\e@@)
1690 .Ve
1691 .PP
1692 then \f(CWmypush()\fR takes arguments exactly like \f(CWpush()\fR does.
1693 .PP
1694 If subroutine signatures are enabled (see "Signatures"), then
1695 the shorter PROTO syntax is unavailable, because it would clash with
1696 signatures. In that case, a prototype can only be declared in the form
1697 of an attribute.
1698 .PP
1699 The
1700 function declaration must be visible at compile time. The prototype
1701 affects only interpretation of regular calls to the function,
1702 where regular is defined as not using the \f(CW\*(C`&\*(C'\fR sigil. In
1703 other words, if you call it like a built-in function, then it behaves
1704 like a built-in function. If you call it like an old-fashioned (perl4)
1705 subroutine, then it behaves like an old-fashioned subroutine. It
1706 naturally falls out from this rule that prototypes have no influence
1707 on subroutine references like \f(CW\*(C`\e&foo\*(C'\fR or on indirect subroutine
1708 calls like \f(CW\*(C`&{$subref}()\*(C'\fR or \f(CW$subref\->()\fR.
1709 .PP
1710 Method calls are not influenced by prototypes either, because the
1711 function to be called is indeterminate at compile time, since
1712 the exact code called depends on inheritance.
1713 .PP
1714 Because the intent of this feature is primarily to let you define
1715 subroutines that work like built-in functions, here are prototypes
1716 for some other functions that parse almost exactly like the
1717 corresponding built-in.
1718 .PP
1719 .Vb 1
1720 \& Declared as Called as
1721 \&
1722 \& sub mylink ($$) mylink $old, $new
1723 \& sub myvec ($$$) myvec $var, $offset, 1
1724 \& sub myindex ($$;$) myindex getstring(), "substr"
1725 \& sub mysyswrite ($$$;$) mysyswrite $buf, 0, length($buf) \- $off, $off
1726 \& sub myreverse (@) myreverse $x, $y, $z
1727 \& sub myjoin ($@) myjoin ":", $x, $y, $z
1728 \& sub mypop (\e@) mypop @array
1729 \& sub mysplice (\e@$$@) mysplice @array, 0, 2, @pushme
1730 \& sub mykeys (\e[%@]) mykeys $hashref\->%*
1731 \& sub myopen (*;$) myopen HANDLE, $name
1732 \& sub mypipe (**) mypipe READHANDLE, WRITEHANDLE
1733 \& sub mygrep (&@) mygrep { /foo/ } $x, $y, $z
1734 \& sub myrand (;$) myrand 42
1735 \& sub mytime () mytime
1736 .Ve
1737 .PP
1738 Any backslashed prototype character represents an actual argument
1739 that must start with that character (optionally preceded by \f(CW\*(C`my\*(C'\fR,
1740 \&\f(CW\*(C`our\*(C'\fR or \f(CW\*(C`local\*(C'\fR), with the exception of \f(CW\*(C`$\*(C'\fR, which will
1741 accept any scalar lvalue expression, such as \f(CW\*(C`$foo = 7\*(C'\fR or
1742 \&\f(CW\*(C`my_function()\->[0]\*(C'\fR. The value passed as part of \f(CW@_\fR will be a
1743 reference to the actual argument given in the subroutine call,
1744 obtained by applying \f(CW\*(C`\e\*(C'\fR to that argument.
1745 .PP
1746 You can use the \f(CW\*(C`\e[]\*(C'\fR backslash group notation to specify more than one
1747 allowed argument type. For example:
1748 .PP
1749 .Vb 1
1750 \& sub myref (\e[$@%&*])
1751 .Ve
1752 .PP
1753 will allow calling \fBmyref()\fR as
1754 .PP
1755 .Vb 5
1756 \& myref $var
1757 \& myref @array
1758 \& myref %hash
1759 \& myref &sub
1760 \& myref *glob
1761 .Ve
1762 .PP
1763 and the first argument of \fBmyref()\fR will be a reference to
1764 a scalar, an array, a hash, a subroutine, or a glob.
1765 .PP
1766 Unbackslashed prototype characters have special meanings. Any
1767 unbackslashed \f(CW\*(C`@\*(C'\fR or \f(CW\*(C`%\*(C'\fR eats all remaining arguments, and forces
1768 list context. An argument represented by \f(CW\*(C`$\*(C'\fR forces scalar context. An
1769 \&\f(CW\*(C`&\*(C'\fR requires an anonymous subroutine, which, if passed as the first
1770 argument, may look like a bare block: It does not require the \f(CW\*(C`sub\*(C'\fR keyword
1771 or a subsequent comma.
1772 .PP
1773 A \f(CW\*(C`*\*(C'\fR allows the subroutine to accept a bareword, constant, scalar expression,
1774 typeglob, or a reference to a typeglob in that slot. The value will be
1775 available to the subroutine either as a simple scalar, or (in the latter
1776 two cases) as a reference to the typeglob. If you wish to always convert
1777 such arguments to a typeglob reference, use \fBSymbol::qualify_to_ref()\fR as
1778 follows:
1779 .PP
1780 .Vb 1
1781 \& use Symbol \*(Aqqualify_to_ref\*(Aq;
1782 \&
1783 \& sub foo (*) {
1784 \& my $fh = qualify_to_ref(shift, caller);
1785 \& ...
1786 \& }
1787 .Ve
1788 .PP
1789 The \f(CW\*(C`+\*(C'\fR prototype is a special alternative to \f(CW\*(C`$\*(C'\fR that will act like
1790 \&\f(CW\*(C`\e[@%]\*(C'\fR when given a literal array or hash variable, but will otherwise
1791 force scalar context on the argument. This is useful for functions which
1792 should accept either a literal array or an array reference as the argument:
1793 .PP
1794 .Vb 5
1795 \& sub mypush (+@) {
1796 \& my $aref = shift;
1797 \& die "Not an array or arrayref" unless ref $aref eq \*(AqARRAY\*(Aq;
1798 \& push @$aref, @_;
1799 \& }
1800 .Ve
1801 .PP
1802 When using the \f(CW\*(C`+\*(C'\fR prototype, your function must check that the argument
1803 is of an acceptable type.
1804 .PP
1805 A semicolon (\f(CW\*(C`;\*(C'\fR) separates mandatory arguments from optional arguments.
1806 It is redundant before \f(CW\*(C`@\*(C'\fR or \f(CW\*(C`%\*(C'\fR, which gobble up everything else.
1807 .PP
1808 As the last character of a prototype, or just before a semicolon, a \f(CW\*(C`@\*(C'\fR
1809 or a \f(CW\*(C`%\*(C'\fR, you can use \f(CW\*(C`_\*(C'\fR in place of \f(CW\*(C`$\*(C'\fR: if this argument is not
1810 provided, \f(CW$_\fR will be used instead.
1811 .PP
1812 Note how the last three examples in the table above are treated
1813 specially by the parser. \f(CWmygrep()\fR is parsed as a true list
1814 operator, \f(CWmyrand()\fR is parsed as a true unary operator with unary
1815 precedence the same as \f(CWrand()\fR, and \f(CWmytime()\fR is truly without
1816 arguments, just like \f(CWtime()\fR. That is, if you say
1817 .PP
1818 .Vb 1
1819 \& mytime +2;
1820 .Ve
1821 .PP
1822 you'll get \f(CW\*(C`mytime() + 2\*(C'\fR, not \f(CWmytime(2)\fR, which is how it would be parsed
1823 without a prototype. If you want to force a unary function to have the
1824 same precedence as a list operator, add \f(CW\*(C`;\*(C'\fR to the end of the prototype:
1825 .PP
1826 .Vb 2
1827 \& sub mygetprotobynumber($;);
1828 \& mygetprotobynumber $x > $y; # parsed as mygetprotobynumber($x > $y)
1829 .Ve
1830 .PP
1831 The interesting thing about \f(CW\*(C`&\*(C'\fR is that you can generate new syntax with it,
1832 provided it's in the initial position:
1833 .IX Xref "&"
1834 .PP
1835 .Vb 9
1836 \& sub try (&@) {
1837 \& my($try,$catch) = @_;
1838 \& eval { &$try };
1839 \& if ($@) {
1840 \& local $_ = $@;
1841 \& &$catch;
1842 \& }
1843 \& }
1844 \& sub catch (&) { $_[0] }
1845 \&
1846 \& try {
1847 \& die "phooey";
1848 \& } catch {
1849 \& /phooey/ and print "unphooey\en";
1850 \& };
1851 .Ve
1852 .PP
1853 That prints \f(CW"unphooey"\fR. (Yes, there are still unresolved
1854 issues having to do with visibility of \f(CW@_\fR. I'm ignoring that
1855 question for the moment. (But note that if we make \f(CW@_\fR lexically
1856 scoped, those anonymous subroutines can act like closures... (Gee,
1857 is this sounding a little Lispish? (Never mind.))))
1858 .PP
1859 And here's a reimplementation of the Perl \f(CW\*(C`grep\*(C'\fR operator:
1860 .IX Xref "grep"
1861 .PP
1862 .Vb 8
1863 \& sub mygrep (&@) {
1864 \& my $code = shift;
1865 \& my @result;
1866 \& foreach $_ (@_) {
1867 \& push(@result, $_) if &$code;
1868 \& }
1869 \& @result;
1870 \& }
1871 .Ve
1872 .PP
1873 Some folks would prefer full alphanumeric prototypes. Alphanumerics have
1874 been intentionally left out of prototypes for the express purpose of
1875 someday in the future adding named, formal parameters. The current
1876 mechanism's main goal is to let module writers provide better diagnostics
1877 for module users. Larry feels the notation quite understandable to Perl
1878 programmers, and that it will not intrude greatly upon the meat of the
1879 module, nor make it harder to read. The line noise is visually
1880 encapsulated into a small pill that's easy to swallow.
1881 .PP
1882 If you try to use an alphanumeric sequence in a prototype you will
1883 generate an optional warning \- "Illegal character in prototype...".
1884 Unfortunately earlier versions of Perl allowed the prototype to be
1885 used as long as its prefix was a valid prototype. The warning may be
1886 upgraded to a fatal error in a future version of Perl once the
1887 majority of offending code is fixed.
1888 .PP
1889 It's probably best to prototype new functions, not retrofit prototyping
1890 into older ones. That's because you must be especially careful about
1891 silent impositions of differing list versus scalar contexts. For example,
1892 if you decide that a function should take just one parameter, like this:
1893 .PP
1894 .Vb 4
1895 \& sub func ($) {
1896 \& my $n = shift;
1897 \& print "you gave me $n\en";
1898 \& }
1899 .Ve
1900 .PP
1901 and someone has been calling it with an array or expression
1902 returning a list:
1903 .PP
1904 .Vb 2
1905 \& func(@foo);
1906 \& func( $text =~ /\ew+/g );
1907 .Ve
1908 .PP
1909 Then you've just supplied an automatic \f(CW\*(C`scalar\*(C'\fR in front of their
1910 argument, which can be more than a bit surprising. The old \f(CW@foo\fR
1911 which used to hold one thing doesn't get passed in. Instead,
1912 \&\f(CWfunc()\fR now gets passed in a \f(CW1\fR; that is, the number of elements
1913 in \f(CW@foo\fR. And the \f(CW\*(C`m//g\*(C'\fR gets called in scalar context so instead of a
1914 list of words it returns a boolean result and advances \f(CWpos($text)\fR. Ouch!
1915 .PP
1916 If a sub has both a PROTO and a BLOCK, the prototype is not applied
1917 until after the BLOCK is completely defined. This means that a recursive
1918 function with a prototype has to be predeclared for the prototype to take
1919 effect, like so:
1920 .PP
1921 .Vb 4
1922 \& sub foo($$);
1923 \& sub foo($$) {
1924 \& foo 1, 2;
1925 \& }
1926 .Ve
1927 .PP
1928 This is all very powerful, of course, and should be used only in moderation
1929 to make the world a better place.
1930 .SS "Constant Functions"
1931 .IX Xref "constant"
1932 .IX Subsection "Constant Functions"
1933 Functions with a prototype of \f(CW\*(C`()\*(C'\fR are potential candidates for
1934 inlining. If the result after optimization and constant folding
1935 is either a constant or a lexically-scoped scalar which has no other
1936 references, then it will be used in place of function calls made
1937 without \f(CW\*(C`&\*(C'\fR. Calls made using \f(CW\*(C`&\*(C'\fR are never inlined. (See
1938 constant for an easy way to declare most constants.)
1939 .PP
1940 The following functions would all be inlined:
1941 .PP
1942 .Vb 5
1943 \& sub pi () { 3.14159 } # Not exact, but close.
1944 \& sub PI () { 4 * atan2 1, 1 } # As good as it gets,
1945 \& # and it\*(Aqs inlined, too!
1946 \& sub ST_DEV () { 0 }
1947 \& sub ST_INO () { 1 }
1948 \&
1949 \& sub FLAG_FOO () { 1 << 8 }
1950 \& sub FLAG_BAR () { 1 << 9 }
1951 \& sub FLAG_MASK () { FLAG_FOO | FLAG_BAR }
1952 \&
1953 \& sub OPT_BAZ () { not (0x1B58 & FLAG_MASK) }
1954 \&
1955 \& sub N () { int(OPT_BAZ) / 3 }
1956 \&
1957 \& sub FOO_SET () { 1 if FLAG_MASK & FLAG_FOO }
1958 \& sub FOO_SET2 () { if (FLAG_MASK & FLAG_FOO) { 1 } }
1959 .Ve
1960 .PP
1961 (Be aware that the last example was not always inlined in Perl 5.20 and
1962 earlier, which did not behave consistently with subroutines containing
1963 inner scopes.) You can countermand inlining by using an explicit
1964 \&\f(CW\*(C`return\*(C'\fR:
1965 .PP
1966 .Vb 9
1967 \& sub baz_val () {
1968 \& if (OPT_BAZ) {
1969 \& return 23;
1970 \& }
1971 \& else {
1972 \& return 42;
1973 \& }
1974 \& }
1975 \& sub bonk_val () { return 12345 }
1976 .Ve
1977 .PP
1978 As alluded to earlier you can also declare inlined subs dynamically at
1979 BEGIN time if their body consists of a lexically-scoped scalar which
1980 has no other references. Only the first example here will be inlined:
1981 .PP
1982 .Vb 5
1983 \& BEGIN {
1984 \& my $var = 1;
1985 \& no strict \*(Aqrefs\*(Aq;
1986 \& *INLINED = sub () { $var };
1987 \& }
1988 \&
1989 \& BEGIN {
1990 \& my $var = 1;
1991 \& my $ref = \e$var;
1992 \& no strict \*(Aqrefs\*(Aq;
1993 \& *NOT_INLINED = sub () { $var };
1994 \& }
1995 .Ve
1996 .PP
1997 A not so obvious caveat with this (see [RT #79908]) is what happens if the
1998 variable is potentially modifiable. For example:
1999 .PP
2000 .Vb 6
2001 \& BEGIN {
2002 \& my $x = 10;
2003 \& *FOO = sub () { $x };
2004 \& $x++;
2005 \& }
2006 \& print FOO(); # printed 10 prior to 5.32.0
2007 .Ve
2008 .PP
2009 From Perl 5.22 onwards this gave a deprecation warning, and from Perl 5.32
2010 onwards it became a run-time error. Previously the variable was
2011 immediately inlined, and stopped behaving like a normal lexical variable;
2012 so it printed \f(CW10\fR, not \f(CW11\fR.
2013 .PP
2014 If you still want such a subroutine to be inlined (with no warning), make
2015 sure the variable is not used in a context where it could be modified
2016 aside from where it is declared.
2017 .PP
2018 .Vb 11
2019 \& # Fine, no warning
2020 \& BEGIN {
2021 \& my $x = 54321;
2022 \& *INLINED = sub () { $x };
2023 \& }
2024 \& # Error
2025 \& BEGIN {
2026 \& my $x;
2027 \& $x = 54321;
2028 \& *ALSO_INLINED = sub () { $x };
2029 \& }
2030 .Ve
2031 .PP
2032 Perl 5.22 also introduced the "const" attribute as an alternative. It was
2033 initially experimental, but made stable in Perl 5.40. When applied to an
2034 anonymous subroutine, it forces the sub to be called when the \f(CW\*(C`sub\*(C'\fR
2035 expression is evaluated. The return value is captured and turned into a
2036 constant subroutine:
2037 .PP
2038 .Vb 3
2039 \& my $x = 54321;
2040 \& *INLINED = sub : const { $x };
2041 \& $x++;
2042 .Ve
2043 .PP
2044 The return value of \f(CW\*(C`INLINED\*(C'\fR in this example will always be 54321,
2045 regardless of later modifications to \f(CW$x\fR. You can also put any arbitrary
2046 code inside the sub, at it will be executed immediately and its return
2047 value captured the same way.
2048 .PP
2049 If you really want a subroutine with a \f(CW\*(C`()\*(C'\fR prototype that returns a
2050 lexical variable you can easily force it to not be inlined by adding
2051 an explicit \f(CW\*(C`return\*(C'\fR:
2052 .PP
2053 .Vb 6
2054 \& BEGIN {
2055 \& my $x = 10;
2056 \& *FOO = sub () { return $x };
2057 \& $x++;
2058 \& }
2059 \& print FOO(); # prints 11
2060 .Ve
2061 .PP
2062 The easiest way to tell if a subroutine was inlined is by using
2063 B::Deparse. Consider this example of two subroutines returning
2064 \&\f(CW1\fR, one with a \f(CW\*(C`()\*(C'\fR prototype causing it to be inlined, and one
2065 without (with deparse output truncated for clarity):
2066 .PP
2067 .Vb 7
2068 \& $ perl \-MO=Deparse \-e \*(Aqsub ONE { 1 } if (ONE) { print ONE if ONE }\*(Aq
2069 \& sub ONE {
2070 \& 1;
2071 \& }
2072 \& if (ONE ) {
2073 \& print ONE() if ONE ;
2074 \& }
2075 \&
2076 \& $ perl \-MO=Deparse \-e \*(Aqsub ONE () { 1 } if (ONE) { print ONE if ONE }\*(Aq
2077 \& sub ONE () { 1 }
2078 \& do {
2079 \& print 1
2080 \& };
2081 .Ve
2082 .PP
2083 If you redefine a subroutine that was eligible for inlining, you'll
2084 get a warning by default. You can use this warning to tell whether or
2085 not a particular subroutine is considered inlinable, since it's
2086 different than the warning for overriding non-inlined subroutines:
2087 .PP
2088 .Vb 4
2089 \& $ perl \-e \*(Aqsub one () {1} sub one () {2}\*(Aq
2090 \& Constant subroutine one redefined at \-e line 1.
2091 \& $ perl \-we \*(Aqsub one {1} sub one {2}\*(Aq
2092 \& Subroutine one redefined at \-e line 1.
2093 .Ve
2094 .PP
2095 The warning is considered severe enough not to be affected by the
2096 \&\fB\-w\fR switch (or its absence) because previously compiled invocations
2097 of the function will still be using the old value of the function. If
2098 you need to be able to redefine the subroutine, you need to ensure
2099 that it isn't inlined, either by dropping the \f(CW\*(C`()\*(C'\fR prototype (which
2100 changes calling semantics, so beware) or by thwarting the inlining
2101 mechanism in some other way, e.g. by adding an explicit \f(CW\*(C`return\*(C'\fR, as
2102 mentioned above:
2103 .PP
2104 .Vb 1
2105 \& sub not_inlined () { return 23 }
2106 .Ve
2107 .SS "Overriding Built-in Functions"
2108 .IX Xref "built-in override CORE CORE::GLOBAL"
2109 .IX Subsection "Overriding Built-in Functions"
2110 Many built-in functions may be overridden, though this should be tried
2111 only occasionally and for good reason. Typically this might be
2112 done by a package attempting to emulate missing built-in functionality
2113 on a non-Unix system.
2114 .PP
2115 Overriding may be done only by importing the name from a module at
2116 compile time\-\-ordinary predeclaration isn't good enough. However, the
2117 \&\f(CW\*(C`use subs\*(C'\fR pragma lets you, in effect, predeclare subs
2118 via the import syntax, and these names may then override built-in ones:
2119 .PP
2120 .Vb 3
2121 \& use subs \*(Aqchdir\*(Aq, \*(Aqchroot\*(Aq, \*(Aqchmod\*(Aq, \*(Aqchown\*(Aq;
2122 \& chdir $somewhere;
2123 \& sub chdir { ... }
2124 .Ve
2125 .PP
2126 To unambiguously refer to the built-in form, precede the
2127 built-in name with the special package qualifier \f(CW\*(C`CORE::\*(C'\fR. For example,
2128 saying \f(CWCORE::open()\fR always refers to the built-in \f(CWopen()\fR, even
2129 if the current package has imported some other subroutine called
2130 \&\f(CW&open()\fR from elsewhere. Even though it looks like a regular
2131 function call, it isn't: the \f(CW\*(C`CORE::\*(C'\fR prefix in that case is part of Perl's
2132 syntax, and works for any keyword, regardless of what is in the \f(CW\*(C`CORE\*(C'\fR
2133 package. Taking a reference to it, that is, \f(CW\*(C`\e&CORE::open\*(C'\fR, only works
2134 for some keywords. See CORE.
2135 .PP
2136 Library modules should not in general export built-in names like \f(CW\*(C`open\*(C'\fR
2137 or \f(CW\*(C`chdir\*(C'\fR as part of their default \f(CW@EXPORT\fR list, because these may
2138 sneak into someone else's namespace and change the semantics unexpectedly.
2139 Instead, if the module adds that name to \f(CW@EXPORT_OK\fR, then it's
2140 possible for a user to import the name explicitly, but not implicitly.
2141 That is, they could say
2142 .PP
2143 .Vb 1
2144 \& use Module \*(Aqopen\*(Aq;
2145 .Ve
2146 .PP
2147 and it would import the \f(CW\*(C`open\*(C'\fR override. But if they said
2148 .PP
2149 .Vb 1
2150 \& use Module;
2151 .Ve
2152 .PP
2153 they would get the default imports without overrides.
2154 .PP
2155 The foregoing mechanism for overriding built-in is restricted, quite
2156 deliberately, to the package that requests the import. There is a second
2157 method that is sometimes applicable when you wish to override a built-in
2158 everywhere, without regard to namespace boundaries. This is achieved by
2159 importing a sub into the special namespace \f(CW\*(C`CORE::GLOBAL::\*(C'\fR. Here is an
2160 example that quite brazenly replaces the \f(CW\*(C`glob\*(C'\fR operator with something
2161 that understands regular expressions.
2162 .PP
2163 .Vb 4
2164 \& package REGlob;
2165 \& require Exporter;
2166 \& @ISA = \*(AqExporter\*(Aq;
2167 \& @EXPORT_OK = \*(Aqglob\*(Aq;
2168 \&
2169 \& sub import {
2170 \& my $pkg = shift;
2171 \& return unless @_;
2172 \& my $sym = shift;
2173 \& my $where = ($sym =~ s/^GLOBAL_// ? \*(AqCORE::GLOBAL\*(Aq : caller(0));
2174 \& $pkg\->export($where, $sym, @_);
2175 \& }
2176 \&
2177 \& sub glob {
2178 \& my $pat = shift;
2179 \& my @got;
2180 \& if (opendir my $d, \*(Aq.\*(Aq) {
2181 \& @got = grep /$pat/, readdir $d;
2182 \& closedir $d;
2183 \& }
2184 \& return @got;
2185 \& }
2186 \& 1;
2187 .Ve
2188 .PP
2189 And here's how it could be (ab)used:
2190 .PP
2191 .Vb 4
2192 \& #use REGlob \*(AqGLOBAL_glob\*(Aq; # override glob() in ALL namespaces
2193 \& package Foo;
2194 \& use REGlob \*(Aqglob\*(Aq; # override glob() in Foo:: only
2195 \& print for <^[a\-z_]+\e.pm\e$>; # show all pragmatic modules
2196 .Ve
2197 .PP
2198 The initial comment shows a contrived, even dangerous example.
2199 By overriding \f(CW\*(C`glob\*(C'\fR globally, you would be forcing the new (and
2200 subversive) behavior for the \f(CW\*(C`glob\*(C'\fR operator for \fIevery\fR namespace,
2201 without the complete cognizance or cooperation of the modules that own
2202 those namespaces. Naturally, this should be done with extreme caution\-\-if
2203 it must be done at all.
2204 .PP
2205 The \f(CW\*(C`REGlob\*(C'\fR example above does not implement all the support needed to
2206 cleanly override Perl's \f(CW\*(C`glob\*(C'\fR operator. The built-in \f(CW\*(C`glob\*(C'\fR has
2207 different behaviors depending on whether it appears in a scalar or list
2208 context, but our \f(CW\*(C`REGlob\*(C'\fR doesn't. Indeed, many Perl built-ins have such
2209 context sensitive behaviors, and these must be adequately supported by
2210 a properly written override. For a fully functional example of overriding
2211 \&\f(CW\*(C`glob\*(C'\fR, study the implementation of \f(CW\*(C`File::DosGlob\*(C'\fR in the standard
2212 library.
2213 .PP
2214 When you override a built-in, your replacement should be consistent (if
2215 possible) with the built-in native syntax. You can achieve this by using
2216 a suitable prototype. To get the prototype of an overridable built-in,
2217 use the \f(CW\*(C`prototype\*(C'\fR function with an argument of \f(CW"CORE::builtin_name"\fR
2218 (see "prototype" in perlfunc).
2219 .PP
2220 Note however that some built-ins can't have their syntax expressed by a
2221 prototype (such as \f(CW\*(C`system\*(C'\fR or \f(CW\*(C`chomp\*(C'\fR). If you override them you won't
2222 be able to fully mimic their original syntax.
2223 .PP
2224 The built-ins \f(CW\*(C`do\*(C'\fR, \f(CW\*(C`require\*(C'\fR and \f(CW\*(C`glob\*(C'\fR can also be overridden, but due
2225 to special magic, their original syntax is preserved, and you don't have
2226 to define a prototype for their replacements. (You can't override the
2227 \&\f(CW\*(C`do BLOCK\*(C'\fR syntax, though).
2228 .PP
2229 \&\f(CW\*(C`require\*(C'\fR has special additional dark magic: if you invoke your
2230 \&\f(CW\*(C`require\*(C'\fR replacement as \f(CW\*(C`require Foo::Bar\*(C'\fR, it will actually receive
2231 the argument \f(CW"Foo/Bar.pm"\fR in \f(CW@_\fR. See "require" in perlfunc.
2232 .PP
2233 And, as you'll have noticed from the previous example, if you override
2234 \&\f(CW\*(C`glob\*(C'\fR, the \f(CW\*(C`<*>\*(C'\fR glob operator is overridden as well.
2235 .PP
2236 In a similar fashion, overriding the \f(CW\*(C`readline\*(C'\fR function also overrides
2237 the equivalent I/O operator \f(CW\*(C`<FILEHANDLE>\*(C'\fR. Also, overriding
2238 \&\f(CW\*(C`readpipe\*(C'\fR also overrides the operators \f(CW\`\`\fR and \f(CW\*(C`qx//\*(C'\fR.
2239 .PP
2240 Finally, some built-ins (e.g. \f(CW\*(C`exists\*(C'\fR or \f(CW\*(C`grep\*(C'\fR) can't be overridden.
2241 .SS Autoloading
2242 .IX Xref "autoloading AUTOLOAD"
2243 .IX Subsection "Autoloading"
2244 If you call a subroutine that is undefined, you would ordinarily
2245 get an immediate, fatal error complaining that the subroutine doesn't
2246 exist. (Likewise for subroutines being used as methods, when the
2247 method doesn't exist in any base class of the class's package.)
2248 However, if an \f(CW\*(C`AUTOLOAD\*(C'\fR subroutine is defined in the package or
2249 packages used to locate the original subroutine, then that
2250 \&\f(CW\*(C`AUTOLOAD\*(C'\fR subroutine is called with the arguments that would have
2251 been passed to the original subroutine. The fully qualified name
2252 of the original subroutine magically appears in the global \f(CW$AUTOLOAD\fR
2253 variable of the same package as the \f(CW\*(C`AUTOLOAD\*(C'\fR routine. The name
2254 is not passed as an ordinary argument because, er, well, just
2255 because, that's why. (As an exception, a method call to a nonexistent
2256 \&\f(CW\*(C`import\*(C'\fR or \f(CW\*(C`unimport\*(C'\fR method is just skipped instead. Also, if
2257 the AUTOLOAD subroutine is an XSUB, there are other ways to retrieve the
2258 subroutine name. See "Autoloading with XSUBs" in perlguts for details.)
2259 .PP
2260 Many \f(CW\*(C`AUTOLOAD\*(C'\fR routines load in a definition for the requested
2261 subroutine using \fBeval()\fR, then execute that subroutine using a special
2262 form of \fBgoto()\fR that erases the stack frame of the \f(CW\*(C`AUTOLOAD\*(C'\fR routine
2263 without a trace. (See the source to the standard module documented
2264 in AutoLoader, for example.) But an \f(CW\*(C`AUTOLOAD\*(C'\fR routine can
2265 also just emulate the routine and never define it. For example,
2266 let's pretend that a function that wasn't defined should just invoke
2267 \&\f(CW\*(C`system\*(C'\fR with those arguments. All you'd do is:
2268 .PP
2269 .Vb 9
2270 \& sub AUTOLOAD {
2271 \& our $AUTOLOAD; # keep \*(Aquse strict\*(Aq happy
2272 \& my $program = $AUTOLOAD;
2273 \& $program =~ s/.*:://;
2274 \& system($program, @_);
2275 \& }
2276 \& date();
2277 \& who();
2278 \& ls(\*(Aq\-l\*(Aq);
2279 .Ve
2280 .PP
2281 In fact, if you predeclare functions you want to call that way, you don't
2282 even need parentheses:
2283 .PP
2284 .Vb 4
2285 \& use subs qw(date who ls);
2286 \& date;
2287 \& who;
2288 \& ls \*(Aq\-l\*(Aq;
2289 .Ve
2290 .PP
2291 A more complete example of this is the Shell module on CPAN, which
2292 can treat undefined subroutine calls as calls to external programs.
2293 .PP
2294 Mechanisms are available to help modules writers split their modules
2295 into autoloadable files. See the standard AutoLoader module
2296 described in AutoLoader and in AutoSplit, the standard
2297 SelfLoader modules in SelfLoader, and the document on adding C
2298 functions to Perl code in perlxs.
2299 .SS "Subroutine Attributes"
2300 .IX Xref "attribute subroutine, attribute attrs"
2301 .IX Subsection "Subroutine Attributes"
2302 A subroutine declaration or definition may have a list of attributes
2303 associated with it. If such an attribute list is present, it is
2304 broken up at space or colon boundaries and treated as though a
2305 \&\f(CW\*(C`use attributes\*(C'\fR had been seen. See attributes for details
2306 about what attributes are currently supported.
2307 Unlike the limitation with the obsolescent \f(CW\*(C`use attrs\*(C'\fR, the
2308 \&\f(CW\*(C`sub : ATTRLIST\*(C'\fR syntax works to associate the attributes with
2309 a pre-declaration, and not just with a subroutine definition.
2310 .PP
2311 The attributes must be valid as simple identifier names (without any
2312 punctuation other than the '_' character). They may have a parameter
2313 list appended, which is only checked for whether its parentheses ('(',')')
2314 nest properly.
2315 .PP
2316 Examples of valid syntax (even though the attributes are unknown):
2317 .PP
2318 .Vb 3
2319 \& sub fnord (&\e%) : switch(10,foo(7,3)) : expensive;
2320 \& sub plugh () : Ugly(\*(Aq\e(") :Bad;
2321 \& sub xyzzy : _5x5 { ... }
2322 .Ve
2323 .PP
2324 Examples of invalid syntax:
2325 .PP
2326 .Vb 5
2327 \& sub fnord : switch(10,foo(); # ()\-string not balanced
2328 \& sub snoid : Ugly(\*(Aq(\*(Aq); # ()\-string not balanced
2329 \& sub xyzzy : 5x5; # "5x5" not a valid identifier
2330 \& sub plugh : Y2::north; # "Y2::north" not a simple identifier
2331 \& sub snurt : foo + bar; # "+" not a colon or space
2332 .Ve
2333 .PP
2334 The attribute list is passed as a list of constant strings to the code
2335 which associates them with the subroutine. In particular, the second example
2336 of valid syntax above currently looks like this in terms of how it's
2337 parsed and invoked:
2338 .PP
2339 .Vb 1
2340 \& use attributes _\|_PACKAGE_\|_, \e&plugh, q[Ugly(\*(Aq\e(")], \*(AqBad\*(Aq;
2341 .Ve
2342 .PP
2343 For further details on attribute lists and their manipulation,
2344 see attributes and Attribute::Handlers.
2345 .SH "SEE ALSO"
2346 .IX Header "SEE ALSO"
2347 See "Function Templates" in perlref for more about references and closures.
2348 See perlxs if you'd like to learn about calling C subroutines from Perl.
2349 See perlembed if you'd like to learn about calling Perl subroutines from C.
2350 See perlmod to learn about bundling up your functions in separate files.
2351 See perlmodlib to learn what library modules come standard on your system.
2352 See perlootut to learn how to make object method calls.