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