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