Debian Codegraph @

upstream/mageia-cauldron/man1/perlsub.1

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