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 To define an anonymous subroutine at runtime:
22
23 $subref = sub BLOCK; # no proto
24 $subref = sub (PROTO) BLOCK; # with proto
25 $subref = sub : ATTRS BLOCK; # with attributes
26 $subref = sub (PROTO) : ATTRS BLOCK; # with proto and attributes
27
28 To import subroutines:
29
30 use MODULE qw(NAME1 NAME2 NAME3);
31
32 To call subroutines:
33
34 NAME(LIST); # & is optional with parentheses.
35 NAME LIST; # Parentheses optional if predeclared/imported.
36 &NAME(LIST); # Circumvent prototypes.
37 &NAME; # Makes current @_ visible to called subroutine.
38
40 Like many languages, Perl provides for user-defined subroutines. These
41 may be located anywhere in the main program, loaded in from other files
42 via the "do", "require", or "use" keywords, or generated on the fly
43 using "eval" or anonymous subroutines. You can even call a function
44 indirectly using a variable containing its name or a CODE reference.
45
46 The Perl model for function call and return values is simple: all
47 functions are passed as parameters one single flat list of scalars, and
48 all functions likewise return to their caller one single flat list of
49 scalars. Any arrays or hashes in these call and return lists will
50 collapse, losing their identities--but you may always use pass-by-
51 reference instead to avoid this. Both call and return lists may
52 contain as many or as few scalar elements as you'd like. (Often a
53 function without an explicit return statement is called a subroutine,
54 but there's really no difference from Perl's perspective.)
55
56 Any arguments passed in show up in the array @_. Therefore, if you
57 called a function with two arguments, those would be stored in $_[0]
58 and $_[1]. The array @_ is a local array, but its elements are aliases
59 for the actual scalar parameters. In particular, if an element $_[0]
60 is updated, the corresponding argument is updated (or an error occurs
61 if it is not updatable). If an argument is an array or hash element
62 which did not exist when the function was called, that element is
63 created only when (and if) it is modified or a reference to it is
64 taken. (Some earlier versions of Perl created the element whether or
65 not the element was assigned to.) Assigning to the whole array @_
66 removes that aliasing, and does not update any arguments.
67
68 A "return" statement may be used to exit a subroutine, optionally
69 specifying the returned value, which will be evaluated in the
70 appropriate context (list, scalar, or void) depending on the context of
71 the subroutine call. If you specify no return value, the subroutine
72 returns an empty list in list context, the undefined value in scalar
73 context, or nothing in void context. If you return one or more
74 aggregates (arrays and hashes), these will be flattened together into
75 one large indistinguishable list.
76
77 If no "return" is found and if the last statement is an expression, its
78 value is returned. If the last statement is a loop control structure
79 like a "foreach" or a "while", the returned value is unspecified. The
80 empty sub returns the empty list.
81
82 Perl does not have named formal parameters. In practice all you do is
83 assign to a "my()" list of these. Variables that aren't declared to be
84 private are global variables. For gory details on creating private
85 variables, see "Private Variables via my()" and "Temporary Values via
86 local()". To create protected environments for a set of functions in a
87 separate package (and probably a separate file), see "Packages" in
88 perlmod.
89
90 Example:
91
92 sub max {
93 my $max = shift(@_);
94 foreach $foo (@_) {
95 $max = $foo if $max < $foo;
96 }
97 return $max;
98 }
99 $bestday = max($mon,$tue,$wed,$thu,$fri);
100
101 Example:
102
103 # get a line, combining continuation lines
104 # that start with whitespace
105
106 sub get_line {
107 $thisline = $lookahead; # global variables!
108 LINE: while (defined($lookahead = <STDIN>)) {
109 if ($lookahead =~ /^[ \t]/) {
110 $thisline .= $lookahead;
111 }
112 else {
113 last LINE;
114 }
115 }
116 return $thisline;
117 }
118
119 $lookahead = <STDIN>; # get first line
120 while (defined($line = get_line())) {
121 ...
122 }
123
124 Assigning to a list of private variables to name your arguments:
125
126 sub maybeset {
127 my($key, $value) = @_;
128 $Foo{$key} = $value unless $Foo{$key};
129 }
130
131 Because the assignment copies the values, this also has the effect of
132 turning call-by-reference into call-by-value. Otherwise a function is
133 free to do in-place modifications of @_ and change its caller's values.
134
135 upcase_in($v1, $v2); # this changes $v1 and $v2
136 sub upcase_in {
137 for (@_) { tr/a-z/A-Z/ }
138 }
139
140 You aren't allowed to modify constants in this way, of course. If an
141 argument were actually literal and you tried to change it, you'd take a
142 (presumably fatal) exception. For example, this won't work:
143
144 upcase_in("frederick");
145
146 It would be much safer if the "upcase_in()" function were written to
147 return a copy of its parameters instead of changing them in place:
148
149 ($v3, $v4) = upcase($v1, $v2); # this doesn't change $v1 and $v2
150 sub upcase {
151 return unless defined wantarray; # void context, do nothing
152 my @parms = @_;
153 for (@parms) { tr/a-z/A-Z/ }
154 return wantarray ? @parms : $parms[0];
155 }
156
157 Notice how this (unprototyped) function doesn't care whether it was
158 passed real scalars or arrays. Perl sees all arguments as one big,
159 long, flat parameter list in @_. This is one area where Perl's simple
160 argument-passing style shines. The "upcase()" function would work
161 perfectly well without changing the "upcase()" definition even if we
162 fed it things like this:
163
164 @newlist = upcase(@list1, @list2);
165 @newlist = upcase( split /:/, $var );
166
167 Do not, however, be tempted to do this:
168
169 (@a, @b) = upcase(@list1, @list2);
170
171 Like the flattened incoming parameter list, the return list is also
172 flattened on return. So all you have managed to do here is stored
173 everything in @a and made @b empty. See "Pass by Reference" for
174 alternatives.
175
176 A subroutine may be called using an explicit "&" prefix. The "&" is
177 optional in modern Perl, as are parentheses if the subroutine has been
178 predeclared. The "&" is not optional when just naming the subroutine,
179 such as when it's used as an argument to defined() or undef(). Nor is
180 it optional when you want to do an indirect subroutine call with a
181 subroutine name or reference using the "&$subref()" or "&{$subref}()"
182 constructs, although the "$subref->()" notation solves that problem.
183 See perlref for more about all that.
184
185 Subroutines may be called recursively. If a subroutine is called using
186 the "&" form, the argument list is optional, and if omitted, no @_
187 array is set up for the subroutine: the @_ array at the time of the
188 call is visible to subroutine instead. This is an efficiency mechanism
189 that new users may wish to avoid.
190
191 &foo(1,2,3); # pass three arguments
192 foo(1,2,3); # the same
193
194 foo(); # pass a null list
195 &foo(); # the same
196
197 &foo; # foo() get current args, like foo(@_) !!
198 foo; # like foo() IFF sub foo predeclared, else "foo"
199
200 Not only does the "&" form make the argument list optional, it also
201 disables any prototype checking on arguments you do provide. This is
202 partly for historical reasons, and partly for having a convenient way
203 to cheat if you know what you're doing. See Prototypes below.
204
205 Subroutines whose names are in all upper case are reserved to the Perl
206 core, as are modules whose names are in all lower case. A subroutine
207 in all capitals is a loosely-held convention meaning it will be called
208 indirectly by the run-time system itself, usually due to a triggered
209 event. Subroutines that do special, pre-defined things include
210 "AUTOLOAD", "CLONE", "DESTROY" plus all functions mentioned in perltie
211 and PerlIO::via.
212
213 The "BEGIN", "UNITCHECK", "CHECK", "INIT" and "END" subroutines are not
214 so much subroutines as named special code blocks, of which you can have
215 more than one in a package, and which you can not call explicitly. See
216 "BEGIN, UNITCHECK, CHECK, INIT and END" in perlmod
217
218 Private Variables via my()
219 Synopsis:
220
221 my $foo; # declare $foo lexically local
222 my (@wid, %get); # declare list of variables local
223 my $foo = "flurp"; # declare $foo lexical, and init it
224 my @oof = @bar; # declare @oof lexical, and init it
225 my $x : Foo = $y; # similar, with an attribute applied
226
227 WARNING: The use of attribute lists on "my" declarations is still
228 evolving. The current semantics and interface are subject to change.
229 See attributes and Attribute::Handlers.
230
231 The "my" operator declares the listed variables to be lexically
232 confined to the enclosing block, conditional ("if/unless/elsif/else"),
233 loop ("for/foreach/while/until/continue"), subroutine, "eval", or
234 "do/require/use"'d file. If more than one value is listed, the list
235 must be placed in parentheses. All listed elements must be legal
236 lvalues. Only alphanumeric identifiers may be lexically
237 scoped--magical built-ins like $/ must currently be "local"ized with
238 "local" instead.
239
240 Unlike dynamic variables created by the "local" operator, lexical
241 variables declared with "my" are totally hidden from the outside world,
242 including any called subroutines. This is true if it's the same
243 subroutine called from itself or elsewhere--every call gets its own
244 copy.
245
246 This doesn't mean that a "my" variable declared in a statically
247 enclosing lexical scope would be invisible. Only dynamic scopes are
248 cut off. For example, the "bumpx()" function below has access to the
249 lexical $x variable because both the "my" and the "sub" occurred at the
250 same scope, presumably file scope.
251
252 my $x = 10;
253 sub bumpx { $x++ }
254
255 An "eval()", however, can see lexical variables of the scope it is
256 being evaluated in, so long as the names aren't hidden by declarations
257 within the "eval()" itself. See perlref.
258
259 The parameter list to my() may be assigned to if desired, which allows
260 you to initialize your variables. (If no initializer is given for a
261 particular variable, it is created with the undefined value.) Commonly
262 this is used to name input parameters to a subroutine. Examples:
263
264 $arg = "fred"; # "global" variable
265 $n = cube_root(27);
266 print "$arg thinks the root is $n\n";
267 fred thinks the root is 3
268
269 sub cube_root {
270 my $arg = shift; # name doesn't matter
271 $arg **= 1/3;
272 return $arg;
273 }
274
275 The "my" is simply a modifier on something you might assign to. So
276 when you do assign to variables in its argument list, "my" doesn't
277 change whether those variables are viewed as a scalar or an array. So
278
279 my ($foo) = <STDIN>; # WRONG?
280 my @FOO = <STDIN>;
281
282 both supply a list context to the right-hand side, while
283
284 my $foo = <STDIN>;
285
286 supplies a scalar context. But the following declares only one
287 variable:
288
289 my $foo, $bar = 1; # WRONG
290
291 That has the same effect as
292
293 my $foo;
294 $bar = 1;
295
296 The declared variable is not introduced (is not visible) until after
297 the current statement. Thus,
298
299 my $x = $x;
300
301 can be used to initialize a new $x with the value of the old $x, and
302 the expression
303
304 my $x = 123 and $x == 123
305
306 is false unless the old $x happened to have the value 123.
307
308 Lexical scopes of control structures are not bounded precisely by the
309 braces that delimit their controlled blocks; control expressions are
310 part of that scope, too. Thus in the loop
311
312 while (my $line = <>) {
313 $line = lc $line;
314 } continue {
315 print $line;
316 }
317
318 the scope of $line extends from its declaration throughout the rest of
319 the loop construct (including the "continue" clause), but not beyond
320 it. Similarly, in the conditional
321
322 if ((my $answer = <STDIN>) =~ /^yes$/i) {
323 user_agrees();
324 } elsif ($answer =~ /^no$/i) {
325 user_disagrees();
326 } else {
327 chomp $answer;
328 die "'$answer' is neither 'yes' nor 'no'";
329 }
330
331 the scope of $answer extends from its declaration through the rest of
332 that conditional, including any "elsif" and "else" clauses, but not
333 beyond it. See "Simple statements" in perlsyn for information on the
334 scope of variables in statements with modifiers.
335
336 The "foreach" loop defaults to scoping its index variable dynamically
337 in the manner of "local". However, if the index variable is prefixed
338 with the keyword "my", or if there is already a lexical by that name in
339 scope, then a new lexical is created instead. Thus in the loop
340
341 for my $i (1, 2, 3) {
342 some_function();
343 }
344
345 the scope of $i extends to the end of the loop, but not beyond it,
346 rendering the value of $i inaccessible within "some_function()".
347
348 Some users may wish to encourage the use of lexically scoped variables.
349 As an aid to catching implicit uses to package variables, which are
350 always global, if you say
351
352 use strict 'vars';
353
354 then any variable mentioned from there to the end of the enclosing
355 block must either refer to a lexical variable, be predeclared via "our"
356 or "use vars", or else must be fully qualified with the package name.
357 A compilation error results otherwise. An inner block may countermand
358 this with "no strict 'vars'".
359
360 A "my" has both a compile-time and a run-time effect. At compile time,
361 the compiler takes notice of it. The principal usefulness of this is
362 to quiet "use strict 'vars'", but it is also essential for generation
363 of closures as detailed in perlref. Actual initialization is delayed
364 until run time, though, so it gets executed at the appropriate time,
365 such as each time through a loop, for example.
366
367 Variables declared with "my" are not part of any package and are
368 therefore never fully qualified with the package name. In particular,
369 you're not allowed to try to make a package variable (or other global)
370 lexical:
371
372 my $pack::var; # ERROR! Illegal syntax
373
374 In fact, a dynamic variable (also known as package or global variables)
375 are still accessible using the fully qualified "::" notation even while
376 a lexical of the same name is also visible:
377
378 package main;
379 local $x = 10;
380 my $x = 20;
381 print "$x and $::x\n";
382
383 That will print out 20 and 10.
384
385 You may declare "my" variables at the outermost scope of a file to hide
386 any such identifiers from the world outside that file. This is similar
387 in spirit to C's static variables when they are used at the file level.
388 To do this with a subroutine requires the use of a closure (an
389 anonymous function that accesses enclosing lexicals). If you want to
390 create a private subroutine that cannot be called from outside that
391 block, it can declare a lexical variable containing an anonymous sub
392 reference:
393
394 my $secret_version = '1.001-beta';
395 my $secret_sub = sub { print $secret_version };
396 &$secret_sub();
397
398 As long as the reference is never returned by any function within the
399 module, no outside module can see the subroutine, because its name is
400 not in any package's symbol table. Remember that it's not REALLY
401 called $some_pack::secret_version or anything; it's just
402 $secret_version, unqualified and unqualifiable.
403
404 This does not work with object methods, however; all object methods
405 have to be in the symbol table of some package to be found. See
406 "Function Templates" in perlref for something of a work-around to this.
407
408 Persistent Private Variables
409 There are two ways to build persistent private variables in Perl 5.10.
410 First, you can simply use the "state" feature. Or, you can use
411 closures, if you want to stay compatible with releases older than 5.10.
412
413 Persistent variables via state()
414
415 Beginning with perl 5.9.4, you can declare variables with the "state"
416 keyword in place of "my". For that to work, though, you must have
417 enabled that feature beforehand, either by using the "feature" pragma,
418 or by using "-E" on one-liners. (see feature)
419
420 For example, the following code maintains a private counter,
421 incremented each time the gimme_another() function is called:
422
423 use feature 'state';
424 sub gimme_another { state $x; return ++$x }
425
426 Also, since $x is lexical, it can't be reached or modified by any Perl
427 code outside.
428
429 When combined with variable declaration, simple scalar assignment to
430 "state" variables (as in "state $x = 42") is executed only the first
431 time. When such statements are evaluated subsequent times, the
432 assignment is ignored. The behavior of this sort of assignment to non-
433 scalar variables is undefined.
434
435 Persistent variables with closures
436
437 Just because a lexical variable is lexically (also called statically)
438 scoped to its enclosing block, "eval", or "do" FILE, this doesn't mean
439 that within a function it works like a C static. It normally works
440 more like a C auto, but with implicit garbage collection.
441
442 Unlike local variables in C or C++, Perl's lexical variables don't
443 necessarily get recycled just because their scope has exited. If
444 something more permanent is still aware of the lexical, it will stick
445 around. So long as something else references a lexical, that lexical
446 won't be freed--which is as it should be. You wouldn't want memory
447 being free until you were done using it, or kept around once you were
448 done. Automatic garbage collection takes care of this for you.
449
450 This means that you can pass back or save away references to lexical
451 variables, whereas to return a pointer to a C auto is a grave error.
452 It also gives us a way to simulate C's function statics. Here's a
453 mechanism for giving a function private variables with both lexical
454 scoping and a static lifetime. If you do want to create something like
455 C's static variables, just enclose the whole function in an extra
456 block, and put the static variable outside the function but in the
457 block.
458
459 {
460 my $secret_val = 0;
461 sub gimme_another {
462 return ++$secret_val;
463 }
464 }
465 # $secret_val now becomes unreachable by the outside
466 # world, but retains its value between calls to gimme_another
467
468 If this function is being sourced in from a separate file via "require"
469 or "use", then this is probably just fine. If it's all in the main
470 program, you'll need to arrange for the "my" to be executed early,
471 either by putting the whole block above your main program, or more
472 likely, placing merely a "BEGIN" code block around it to make sure it
473 gets executed before your program starts to run:
474
475 BEGIN {
476 my $secret_val = 0;
477 sub gimme_another {
478 return ++$secret_val;
479 }
480 }
481
482 See "BEGIN, UNITCHECK, CHECK, INIT and END" in perlmod about the
483 special triggered code blocks, "BEGIN", "UNITCHECK", "CHECK", "INIT"
484 and "END".
485
486 If declared at the outermost scope (the file scope), then lexicals work
487 somewhat like C's file statics. They are available to all functions in
488 that same file declared below them, but are inaccessible from outside
489 that file. This strategy is sometimes used in modules to create
490 private variables that the whole module can see.
491
492 Temporary Values via local()
493 WARNING: In general, you should be using "my" instead of "local",
494 because it's faster and safer. Exceptions to this include the global
495 punctuation variables, global filehandles and formats, and direct
496 manipulation of the Perl symbol table itself. "local" is mostly used
497 when the current value of a variable must be visible to called
498 subroutines.
499
500 Synopsis:
501
502 # localization of values
503
504 local $foo; # make $foo dynamically local
505 local (@wid, %get); # make list of variables local
506 local $foo = "flurp"; # make $foo dynamic, and init it
507 local @oof = @bar; # make @oof dynamic, and init it
508
509 local $hash{key} = "val"; # sets a local value for this hash entry
510 delete local $hash{key}; # delete this entry for the current block
511 local ($cond ? $v1 : $v2); # several types of lvalues support
512 # localization
513
514 # localization of symbols
515
516 local *FH; # localize $FH, @FH, %FH, &FH ...
517 local *merlyn = *randal; # now $merlyn is really $randal, plus
518 # @merlyn is really @randal, etc
519 local *merlyn = 'randal'; # SAME THING: promote 'randal' to *randal
520 local *merlyn = \$randal; # just alias $merlyn, not @merlyn etc
521
522 A "local" modifies its listed variables to be "local" to the enclosing
523 block, "eval", or "do FILE"--and to any subroutine called from within
524 that block. A "local" just gives temporary values to global (meaning
525 package) variables. It does not create a local variable. This is
526 known as dynamic scoping. Lexical scoping is done with "my", which
527 works more like C's auto declarations.
528
529 Some types of lvalues can be localized as well : hash and array
530 elements and slices, conditionals (provided that their result is always
531 localizable), and symbolic references. As for simple variables, this
532 creates new, dynamically scoped values.
533
534 If more than one variable or expression is given to "local", they must
535 be placed in parentheses. This operator works by saving the current
536 values of those variables in its argument list on a hidden stack and
537 restoring them upon exiting the block, subroutine, or eval. This means
538 that called subroutines can also reference the local variable, but not
539 the global one. The argument list may be assigned to if desired, which
540 allows you to initialize your local variables. (If no initializer is
541 given for a particular variable, it is created with an undefined
542 value.)
543
544 Because "local" is a run-time operator, it gets executed each time
545 through a loop. Consequently, it's more efficient to localize your
546 variables outside the loop.
547
548 Grammatical note on local()
549
550 A "local" is simply a modifier on an lvalue expression. When you
551 assign to a "local"ized variable, the "local" doesn't change whether
552 its list is viewed as a scalar or an array. So
553
554 local($foo) = <STDIN>;
555 local @FOO = <STDIN>;
556
557 both supply a list context to the right-hand side, while
558
559 local $foo = <STDIN>;
560
561 supplies a scalar context.
562
563 Localization of special variables
564
565 If you localize a special variable, you'll be giving a new value to it,
566 but its magic won't go away. That means that all side-effects related
567 to this magic still work with the localized value.
568
569 This feature allows code like this to work :
570
571 # Read the whole contents of FILE in $slurp
572 { local $/ = undef; $slurp = <FILE>; }
573
574 Note, however, that this restricts localization of some values ; for
575 example, the following statement dies, as of perl 5.9.0, with an error
576 Modification of a read-only value attempted, because the $1 variable is
577 magical and read-only :
578
579 local $1 = 2;
580
581 Similarly, but in a way more difficult to spot, the following snippet
582 will die in perl 5.9.0 :
583
584 sub f { local $_ = "foo"; print }
585 for ($1) {
586 # now $_ is aliased to $1, thus is magic and readonly
587 f();
588 }
589
590 See next section for an alternative to this situation.
591
592 WARNING: Localization of tied arrays and hashes does not currently work
593 as described. This will be fixed in a future release of Perl; in the
594 meantime, avoid code that relies on any particular behaviour of
595 localising tied arrays or hashes (localising individual elements is
596 still okay). See "Localising Tied Arrays and Hashes Is Broken" in
597 perl58delta for more details.
598
599 Localization of globs
600
601 The construct
602
603 local *name;
604
605 creates a whole new symbol table entry for the glob "name" in the
606 current package. That means that all variables in its glob slot
607 ($name, @name, %name, &name, and the "name" filehandle) are dynamically
608 reset.
609
610 This implies, among other things, that any magic eventually carried by
611 those variables is locally lost. In other words, saying "local */"
612 will not have any effect on the internal value of the input record
613 separator.
614
615 Notably, if you want to work with a brand new value of the default
616 scalar $_, and avoid the potential problem listed above about $_
617 previously carrying a magic value, you should use "local *_" instead of
618 "local $_". As of perl 5.9.1, you can also use the lexical form of $_
619 (declaring it with "my $_"), which avoids completely this problem.
620
621 Localization of elements of composite types
622
623 It's also worth taking a moment to explain what happens when you
624 "local"ize a member of a composite type (i.e. an array or hash
625 element). In this case, the element is "local"ized by name. This means
626 that when the scope of the "local()" ends, the saved value will be
627 restored to the hash element whose key was named in the "local()", or
628 the array element whose index was named in the "local()". If that
629 element was deleted while the "local()" was in effect (e.g. by a
630 "delete()" from a hash or a "shift()" of an array), it will spring back
631 into existence, possibly extending an array and filling in the skipped
632 elements with "undef". For instance, if you say
633
634 %hash = ( 'This' => 'is', 'a' => 'test' );
635 @ary = ( 0..5 );
636 {
637 local($ary[5]) = 6;
638 local($hash{'a'}) = 'drill';
639 while (my $e = pop(@ary)) {
640 print "$e . . .\n";
641 last unless $e > 3;
642 }
643 if (@ary) {
644 $hash{'only a'} = 'test';
645 delete $hash{'a'};
646 }
647 }
648 print join(' ', map { "$_ $hash{$_}" } sort keys %hash),".\n";
649 print "The array has ",scalar(@ary)," elements: ",
650 join(', ', map { defined $_ ? $_ : 'undef' } @ary),"\n";
651
652 Perl will print
653
654 6 . . .
655 4 . . .
656 3 . . .
657 This is a test only a test.
658 The array has 6 elements: 0, 1, 2, undef, undef, 5
659
660 The behavior of local() on non-existent members of composite types is
661 subject to change in future.
662
663 Localized deletion of elements of composite types
664
665 You can use the "delete local $array[$idx]" and "delete local
666 $hash{key}" constructs to delete a composite type entry for the current
667 block and restore it when it ends. They return the array/hash value
668 before the localization, which means that they are respectively
669 equivalent to
670
671 do {
672 my $val = $array[$idx];
673 local $array[$idx];
674 delete $array[$idx];
675 $val
676 }
677
678 and
679
680 do {
681 my $val = $hash{key};
682 local $hash{key};
683 delete $hash{key};
684 $val
685 }
686
687 except that for those the "local" is scoped to the "do" block. Slices
688 are also accepted.
689
690 my %hash = (
691 a => [ 7, 8, 9 ],
692 b => 1,
693 )
694
695 {
696 my $a = delete local $hash{a};
697 # $a is [ 7, 8, 9 ]
698 # %hash is (b => 1)
699
700 {
701 my @nums = delete local @$a[0, 2]
702 # @nums is (7, 9)
703 # $a is [ undef, 8 ]
704
705 $a[0] = 999; # will be erased when the scope ends
706 }
707 # $a is back to [ 7, 8, 9 ]
708
709 }
710 # %hash is back to its original state
711
712 Lvalue subroutines
713 WARNING: Lvalue subroutines are still experimental and the
714 implementation may change in future versions of Perl.
715
716 It is possible to return a modifiable value from a subroutine. To do
717 this, you have to declare the subroutine to return an lvalue.
718
719 my $val;
720 sub canmod : lvalue {
721 # return $val; this doesn't work, don't say "return"
722 $val;
723 }
724 sub nomod {
725 $val;
726 }
727
728 canmod() = 5; # assigns to $val
729 nomod() = 5; # ERROR
730
731 The scalar/list context for the subroutine and for the right-hand side
732 of assignment is determined as if the subroutine call is replaced by a
733 scalar. For example, consider:
734
735 data(2,3) = get_data(3,4);
736
737 Both subroutines here are called in a scalar context, while in:
738
739 (data(2,3)) = get_data(3,4);
740
741 and in:
742
743 (data(2),data(3)) = get_data(3,4);
744
745 all the subroutines are called in a list context.
746
747 Lvalue subroutines are EXPERIMENTAL
748 They appear to be convenient, but there are several reasons to be
749 circumspect.
750
751 You can't use the return keyword, you must pass out the value
752 before falling out of subroutine scope. (see comment in example
753 above). This is usually not a problem, but it disallows an
754 explicit return out of a deeply nested loop, which is sometimes a
755 nice way out.
756
757 They violate encapsulation. A normal mutator can check the
758 supplied argument before setting the attribute it is protecting, an
759 lvalue subroutine never gets that chance. Consider;
760
761 my $some_array_ref = []; # protected by mutators ??
762
763 sub set_arr { # normal mutator
764 my $val = shift;
765 die("expected array, you supplied ", ref $val)
766 unless ref $val eq 'ARRAY';
767 $some_array_ref = $val;
768 }
769 sub set_arr_lv : lvalue { # lvalue mutator
770 $some_array_ref;
771 }
772
773 # set_arr_lv cannot stop this !
774 set_arr_lv() = { a => 1 };
775
776 Passing Symbol Table Entries (typeglobs)
777 WARNING: The mechanism described in this section was originally the
778 only way to simulate pass-by-reference in older versions of Perl.
779 While it still works fine in modern versions, the new reference
780 mechanism is generally easier to work with. See below.
781
782 Sometimes you don't want to pass the value of an array to a subroutine
783 but rather the name of it, so that the subroutine can modify the global
784 copy of it rather than working with a local copy. In perl you can
785 refer to all objects of a particular name by prefixing the name with a
786 star: *foo. This is often known as a "typeglob", because the star on
787 the front can be thought of as a wildcard match for all the funny
788 prefix characters on variables and subroutines and such.
789
790 When evaluated, the typeglob produces a scalar value that represents
791 all the objects of that name, including any filehandle, format, or
792 subroutine. When assigned to, it causes the name mentioned to refer to
793 whatever "*" value was assigned to it. Example:
794
795 sub doubleary {
796 local(*someary) = @_;
797 foreach $elem (@someary) {
798 $elem *= 2;
799 }
800 }
801 doubleary(*foo);
802 doubleary(*bar);
803
804 Scalars are already passed by reference, so you can modify scalar
805 arguments without using this mechanism by referring explicitly to $_[0]
806 etc. You can modify all the elements of an array by passing all the
807 elements as scalars, but you have to use the "*" mechanism (or the
808 equivalent reference mechanism) to "push", "pop", or change the size of
809 an array. It will certainly be faster to pass the typeglob (or
810 reference).
811
812 Even if you don't want to modify an array, this mechanism is useful for
813 passing multiple arrays in a single LIST, because normally the LIST
814 mechanism will merge all the array values so that you can't extract out
815 the individual arrays. For more on typeglobs, see "Typeglobs and
816 Filehandles" in perldata.
817
818 When to Still Use local()
819 Despite the existence of "my", there are still three places where the
820 "local" operator still shines. In fact, in these three places, you
821 must use "local" instead of "my".
822
823 1. You need to give a global variable a temporary value, especially
824 $_.
825
826 The global variables, like @ARGV or the punctuation variables, must
827 be "local"ized with "local()". This block reads in /etc/motd, and
828 splits it up into chunks separated by lines of equal signs, which
829 are placed in @Fields.
830
831 {
832 local @ARGV = ("/etc/motd");
833 local $/ = undef;
834 local $_ = <>;
835 @Fields = split /^\s*=+\s*$/;
836 }
837
838 It particular, it's important to "local"ize $_ in any routine that
839 assigns to it. Look out for implicit assignments in "while"
840 conditionals.
841
842 2. You need to create a local file or directory handle or a local
843 function.
844
845 A function that needs a filehandle of its own must use "local()" on
846 a complete typeglob. This can be used to create new symbol table
847 entries:
848
849 sub ioqueue {
850 local (*READER, *WRITER); # not my!
851 pipe (READER, WRITER) or die "pipe: $!";
852 return (*READER, *WRITER);
853 }
854 ($head, $tail) = ioqueue();
855
856 See the Symbol module for a way to create anonymous symbol table
857 entries.
858
859 Because assignment of a reference to a typeglob creates an alias,
860 this can be used to create what is effectively a local function, or
861 at least, a local alias.
862
863 {
864 local *grow = \&shrink; # only until this block exists
865 grow(); # really calls shrink()
866 move(); # if move() grow()s, it shrink()s too
867 }
868 grow(); # get the real grow() again
869
870 See "Function Templates" in perlref for more about manipulating
871 functions by name in this way.
872
873 3. You want to temporarily change just one element of an array or
874 hash.
875
876 You can "local"ize just one element of an aggregate. Usually this
877 is done on dynamics:
878
879 {
880 local $SIG{INT} = 'IGNORE';
881 funct(); # uninterruptible
882 }
883 # interruptibility automatically restored here
884
885 But it also works on lexically declared aggregates. Prior to
886 5.005, this operation could on occasion misbehave.
887
888 Pass by Reference
889 If you want to pass more than one array or hash into a function--or
890 return them from it--and have them maintain their integrity, then
891 you're going to have to use an explicit pass-by-reference. Before you
892 do that, you need to understand references as detailed in perlref.
893 This section may not make much sense to you otherwise.
894
895 Here are a few simple examples. First, let's pass in several arrays to
896 a function and have it "pop" all of then, returning a new list of all
897 their former last elements:
898
899 @tailings = popmany ( \@a, \@b, \@c, \@d );
900
901 sub popmany {
902 my $aref;
903 my @retlist = ();
904 foreach $aref ( @_ ) {
905 push @retlist, pop @$aref;
906 }
907 return @retlist;
908 }
909
910 Here's how you might write a function that returns a list of keys
911 occurring in all the hashes passed to it:
912
913 @common = inter( \%foo, \%bar, \%joe );
914 sub inter {
915 my ($k, $href, %seen); # locals
916 foreach $href (@_) {
917 while ( $k = each %$href ) {
918 $seen{$k}++;
919 }
920 }
921 return grep { $seen{$_} == @_ } keys %seen;
922 }
923
924 So far, we're using just the normal list return mechanism. What
925 happens if you want to pass or return a hash? Well, if you're using
926 only one of them, or you don't mind them concatenating, then the normal
927 calling convention is ok, although a little expensive.
928
929 Where people get into trouble is here:
930
931 (@a, @b) = func(@c, @d);
932 or
933 (%a, %b) = func(%c, %d);
934
935 That syntax simply won't work. It sets just @a or %a and clears the @b
936 or %b. Plus the function didn't get passed into two separate arrays or
937 hashes: it got one long list in @_, as always.
938
939 If you can arrange for everyone to deal with this through references,
940 it's cleaner code, although not so nice to look at. Here's a function
941 that takes two array references as arguments, returning the two array
942 elements in order of how many elements they have in them:
943
944 ($aref, $bref) = func(\@c, \@d);
945 print "@$aref has more than @$bref\n";
946 sub func {
947 my ($cref, $dref) = @_;
948 if (@$cref > @$dref) {
949 return ($cref, $dref);
950 } else {
951 return ($dref, $cref);
952 }
953 }
954
955 It turns out that you can actually do this also:
956
957 (*a, *b) = func(\@c, \@d);
958 print "@a has more than @b\n";
959 sub func {
960 local (*c, *d) = @_;
961 if (@c > @d) {
962 return (\@c, \@d);
963 } else {
964 return (\@d, \@c);
965 }
966 }
967
968 Here we're using the typeglobs to do symbol table aliasing. It's a tad
969 subtle, though, and also won't work if you're using "my" variables,
970 because only globals (even in disguise as "local"s) are in the symbol
971 table.
972
973 If you're passing around filehandles, you could usually just use the
974 bare typeglob, like *STDOUT, but typeglobs references work, too. For
975 example:
976
977 splutter(\*STDOUT);
978 sub splutter {
979 my $fh = shift;
980 print $fh "her um well a hmmm\n";
981 }
982
983 $rec = get_rec(\*STDIN);
984 sub get_rec {
985 my $fh = shift;
986 return scalar <$fh>;
987 }
988
989 If you're planning on generating new filehandles, you could do this.
990 Notice to pass back just the bare *FH, not its reference.
991
992 sub openit {
993 my $path = shift;
994 local *FH;
995 return open (FH, $path) ? *FH : undef;
996 }
997
998 Prototypes
999 Perl supports a very limited kind of compile-time argument checking
1000 using function prototyping. If you declare
1001
1002 sub mypush (\@@)
1003
1004 then "mypush()" takes arguments exactly like "push()" does. The
1005 function declaration must be visible at compile time. The prototype
1006 affects only interpretation of new-style calls to the function, where
1007 new-style is defined as not using the "&" character. In other words,
1008 if you call it like a built-in function, then it behaves like a built-
1009 in function. If you call it like an old-fashioned subroutine, then it
1010 behaves like an old-fashioned subroutine. It naturally falls out from
1011 this rule that prototypes have no influence on subroutine references
1012 like "\&foo" or on indirect subroutine calls like "&{$subref}" or
1013 "$subref->()".
1014
1015 Method calls are not influenced by prototypes either, because the
1016 function to be called is indeterminate at compile time, since the exact
1017 code called depends on inheritance.
1018
1019 Because the intent of this feature is primarily to let you define
1020 subroutines that work like built-in functions, here are prototypes for
1021 some other functions that parse almost exactly like the corresponding
1022 built-in.
1023
1024 Declared as Called as
1025
1026 sub mylink ($$) mylink $old, $new
1027 sub myvec ($$$) myvec $var, $offset, 1
1028 sub myindex ($$;$) myindex &getstring, "substr"
1029 sub mysyswrite ($$$;$) mysyswrite $buf, 0, length($buf) - $off, $off
1030 sub myreverse (@) myreverse $a, $b, $c
1031 sub myjoin ($@) myjoin ":", $a, $b, $c
1032 sub mypop (\@) mypop @array
1033 sub mysplice (\@$$@) mysplice @array, 0, 2, @pushme
1034 sub mykeys (\%) mykeys %{$hashref}
1035 sub myopen (*;$) myopen HANDLE, $name
1036 sub mypipe (**) mypipe READHANDLE, WRITEHANDLE
1037 sub mygrep (&@) mygrep { /foo/ } $a, $b, $c
1038 sub myrand (;$) myrand 42
1039 sub mytime () mytime
1040
1041 Any backslashed prototype character represents an actual argument that
1042 absolutely must start with that character. The value passed as part of
1043 @_ will be a reference to the actual argument given in the subroutine
1044 call, obtained by applying "\" to that argument.
1045
1046 You can also backslash several argument types simultaneously by using
1047 the "\[]" notation:
1048
1049 sub myref (\[$@%&*])
1050
1051 will allow calling myref() as
1052
1053 myref $var
1054 myref @array
1055 myref %hash
1056 myref &sub
1057 myref *glob
1058
1059 and the first argument of myref() will be a reference to a scalar, an
1060 array, a hash, a code, or a glob.
1061
1062 Unbackslashed prototype characters have special meanings. Any
1063 unbackslashed "@" or "%" eats all remaining arguments, and forces list
1064 context. An argument represented by "$" forces scalar context. An "&"
1065 requires an anonymous subroutine, which, if passed as the first
1066 argument, does not require the "sub" keyword or a subsequent comma.
1067
1068 A "*" allows the subroutine to accept a bareword, constant, scalar
1069 expression, typeglob, or a reference to a typeglob in that slot. The
1070 value will be available to the subroutine either as a simple scalar, or
1071 (in the latter two cases) as a reference to the typeglob. If you wish
1072 to always convert such arguments to a typeglob reference, use
1073 Symbol::qualify_to_ref() as follows:
1074
1075 use Symbol 'qualify_to_ref';
1076
1077 sub foo (*) {
1078 my $fh = qualify_to_ref(shift, caller);
1079 ...
1080 }
1081
1082 A semicolon (";") separates mandatory arguments from optional
1083 arguments. It is redundant before "@" or "%", which gobble up
1084 everything else.
1085
1086 As the last character of a prototype, or just before a semicolon, you
1087 can use "_" in place of "$": if this argument is not provided, $_ will
1088 be used instead.
1089
1090 Note how the last three examples in the table above are treated
1091 specially by the parser. "mygrep()" is parsed as a true list operator,
1092 "myrand()" is parsed as a true unary operator with unary precedence the
1093 same as "rand()", and "mytime()" is truly without arguments, just like
1094 "time()". That is, if you say
1095
1096 mytime +2;
1097
1098 you'll get "mytime() + 2", not mytime(2), which is how it would be
1099 parsed without a prototype.
1100
1101 The interesting thing about "&" is that you can generate new syntax
1102 with it, provided it's in the initial position:
1103
1104 sub try (&@) {
1105 my($try,$catch) = @_;
1106 eval { &$try };
1107 if ($@) {
1108 local $_ = $@;
1109 &$catch;
1110 }
1111 }
1112 sub catch (&) { $_[0] }
1113
1114 try {
1115 die "phooey";
1116 } catch {
1117 /phooey/ and print "unphooey\n";
1118 };
1119
1120 That prints "unphooey". (Yes, there are still unresolved issues having
1121 to do with visibility of @_. I'm ignoring that question for the
1122 moment. (But note that if we make @_ lexically scoped, those anonymous
1123 subroutines can act like closures... (Gee, is this sounding a little
1124 Lispish? (Never mind.))))
1125
1126 And here's a reimplementation of the Perl "grep" operator:
1127
1128 sub mygrep (&@) {
1129 my $code = shift;
1130 my @result;
1131 foreach $_ (@_) {
1132 push(@result, $_) if &$code;
1133 }
1134 @result;
1135 }
1136
1137 Some folks would prefer full alphanumeric prototypes. Alphanumerics
1138 have been intentionally left out of prototypes for the express purpose
1139 of someday in the future adding named, formal parameters. The current
1140 mechanism's main goal is to let module writers provide better
1141 diagnostics for module users. Larry feels the notation quite
1142 understandable to Perl programmers, and that it will not intrude
1143 greatly upon the meat of the module, nor make it harder to read. The
1144 line noise is visually encapsulated into a small pill that's easy to
1145 swallow.
1146
1147 If you try to use an alphanumeric sequence in a prototype you will
1148 generate an optional warning - "Illegal character in prototype...".
1149 Unfortunately earlier versions of Perl allowed the prototype to be used
1150 as long as its prefix was a valid prototype. The warning may be
1151 upgraded to a fatal error in a future version of Perl once the majority
1152 of offending code is fixed.
1153
1154 It's probably best to prototype new functions, not retrofit prototyping
1155 into older ones. That's because you must be especially careful about
1156 silent impositions of differing list versus scalar contexts. For
1157 example, if you decide that a function should take just one parameter,
1158 like this:
1159
1160 sub func ($) {
1161 my $n = shift;
1162 print "you gave me $n\n";
1163 }
1164
1165 and someone has been calling it with an array or expression returning a
1166 list:
1167
1168 func(@foo);
1169 func( split /:/ );
1170
1171 Then you've just supplied an automatic "scalar" in front of their
1172 argument, which can be more than a bit surprising. The old @foo which
1173 used to hold one thing doesn't get passed in. Instead, "func()" now
1174 gets passed in a 1; that is, the number of elements in @foo. And the
1175 "split" gets called in scalar context so it starts scribbling on your
1176 @_ parameter list. Ouch!
1177
1178 This is all very powerful, of course, and should be used only in
1179 moderation to make the world a better place.
1180
1181 Constant Functions
1182 Functions with a prototype of "()" are potential candidates for
1183 inlining. If the result after optimization and constant folding is
1184 either a constant or a lexically-scoped scalar which has no other
1185 references, then it will be used in place of function calls made
1186 without "&". Calls made using "&" are never inlined. (See constant.pm
1187 for an easy way to declare most constants.)
1188
1189 The following functions would all be inlined:
1190
1191 sub pi () { 3.14159 } # Not exact, but close.
1192 sub PI () { 4 * atan2 1, 1 } # As good as it gets,
1193 # and it's inlined, too!
1194 sub ST_DEV () { 0 }
1195 sub ST_INO () { 1 }
1196
1197 sub FLAG_FOO () { 1 << 8 }
1198 sub FLAG_BAR () { 1 << 9 }
1199 sub FLAG_MASK () { FLAG_FOO | FLAG_BAR }
1200
1201 sub OPT_BAZ () { not (0x1B58 & FLAG_MASK) }
1202
1203 sub N () { int(OPT_BAZ) / 3 }
1204
1205 sub FOO_SET () { 1 if FLAG_MASK & FLAG_FOO }
1206
1207 Be aware that these will not be inlined; as they contain inner scopes,
1208 the constant folding doesn't reduce them to a single constant:
1209
1210 sub foo_set () { if (FLAG_MASK & FLAG_FOO) { 1 } }
1211
1212 sub baz_val () {
1213 if (OPT_BAZ) {
1214 return 23;
1215 }
1216 else {
1217 return 42;
1218 }
1219 }
1220
1221 If you redefine a subroutine that was eligible for inlining, you'll get
1222 a mandatory warning. (You can use this warning to tell whether or not
1223 a particular subroutine is considered constant.) The warning is
1224 considered severe enough not to be optional because previously compiled
1225 invocations of the function will still be using the old value of the
1226 function. If you need to be able to redefine the subroutine, you need
1227 to ensure that it isn't inlined, either by dropping the "()" prototype
1228 (which changes calling semantics, so beware) or by thwarting the
1229 inlining mechanism in some other way, such as
1230
1231 sub not_inlined () {
1232 23 if $];
1233 }
1234
1235 Overriding Built-in Functions
1236 Many built-in functions may be overridden, though this should be tried
1237 only occasionally and for good reason. Typically this might be done by
1238 a package attempting to emulate missing built-in functionality on a
1239 non-Unix system.
1240
1241 Overriding may be done only by importing the name from a module at
1242 compile time--ordinary predeclaration isn't good enough. However, the
1243 "use subs" pragma lets you, in effect, predeclare subs via the import
1244 syntax, and these names may then override built-in ones:
1245
1246 use subs 'chdir', 'chroot', 'chmod', 'chown';
1247 chdir $somewhere;
1248 sub chdir { ... }
1249
1250 To unambiguously refer to the built-in form, precede the built-in name
1251 with the special package qualifier "CORE::". For example, saying
1252 "CORE::open()" always refers to the built-in "open()", even if the
1253 current package has imported some other subroutine called "&open()"
1254 from elsewhere. Even though it looks like a regular function call, it
1255 isn't: you can't take a reference to it, such as the incorrect
1256 "\&CORE::open" might appear to produce.
1257
1258 Library modules should not in general export built-in names like "open"
1259 or "chdir" as part of their default @EXPORT list, because these may
1260 sneak into someone else's namespace and change the semantics
1261 unexpectedly. Instead, if the module adds that name to @EXPORT_OK,
1262 then it's possible for a user to import the name explicitly, but not
1263 implicitly. That is, they could say
1264
1265 use Module 'open';
1266
1267 and it would import the "open" override. But if they said
1268
1269 use Module;
1270
1271 they would get the default imports without overrides.
1272
1273 The foregoing mechanism for overriding built-in is restricted, quite
1274 deliberately, to the package that requests the import. There is a
1275 second method that is sometimes applicable when you wish to override a
1276 built-in everywhere, without regard to namespace boundaries. This is
1277 achieved by importing a sub into the special namespace
1278 "CORE::GLOBAL::". Here is an example that quite brazenly replaces the
1279 "glob" operator with something that understands regular expressions.
1280
1281 package REGlob;
1282 require Exporter;
1283 @ISA = 'Exporter';
1284 @EXPORT_OK = 'glob';
1285
1286 sub import {
1287 my $pkg = shift;
1288 return unless @_;
1289 my $sym = shift;
1290 my $where = ($sym =~ s/^GLOBAL_// ? 'CORE::GLOBAL' : caller(0));
1291 $pkg->export($where, $sym, @_);
1292 }
1293
1294 sub glob {
1295 my $pat = shift;
1296 my @got;
1297 if (opendir my $d, '.') {
1298 @got = grep /$pat/, readdir $d;
1299 closedir $d;
1300 }
1301 return @got;
1302 }
1303 1;
1304
1305 And here's how it could be (ab)used:
1306
1307 #use REGlob 'GLOBAL_glob'; # override glob() in ALL namespaces
1308 package Foo;
1309 use REGlob 'glob'; # override glob() in Foo:: only
1310 print for <^[a-z_]+\.pm\$>; # show all pragmatic modules
1311
1312 The initial comment shows a contrived, even dangerous example. By
1313 overriding "glob" globally, you would be forcing the new (and
1314 subversive) behavior for the "glob" operator for every namespace,
1315 without the complete cognizance or cooperation of the modules that own
1316 those namespaces. Naturally, this should be done with extreme
1317 caution--if it must be done at all.
1318
1319 The "REGlob" example above does not implement all the support needed to
1320 cleanly override perl's "glob" operator. The built-in "glob" has
1321 different behaviors depending on whether it appears in a scalar or list
1322 context, but our "REGlob" doesn't. Indeed, many perl built-in have
1323 such context sensitive behaviors, and these must be adequately
1324 supported by a properly written override. For a fully functional
1325 example of overriding "glob", study the implementation of
1326 "File::DosGlob" in the standard library.
1327
1328 When you override a built-in, your replacement should be consistent (if
1329 possible) with the built-in native syntax. You can achieve this by
1330 using a suitable prototype. To get the prototype of an overridable
1331 built-in, use the "prototype" function with an argument of
1332 "CORE::builtin_name" (see "prototype" in perlfunc).
1333
1334 Note however that some built-ins can't have their syntax expressed by a
1335 prototype (such as "system" or "chomp"). If you override them you
1336 won't be able to fully mimic their original syntax.
1337
1338 The built-ins "do", "require" and "glob" can also be overridden, but
1339 due to special magic, their original syntax is preserved, and you don't
1340 have to define a prototype for their replacements. (You can't override
1341 the "do BLOCK" syntax, though).
1342
1343 "require" has special additional dark magic: if you invoke your
1344 "require" replacement as "require Foo::Bar", it will actually receive
1345 the argument "Foo/Bar.pm" in @_. See "require" in perlfunc.
1346
1347 And, as you'll have noticed from the previous example, if you override
1348 "glob", the "<*>" glob operator is overridden as well.
1349
1350 In a similar fashion, overriding the "readline" function also overrides
1351 the equivalent I/O operator "<FILEHANDLE>". Also, overriding "readpipe"
1352 also overrides the operators "``" and "qx//".
1353
1354 Finally, some built-ins (e.g. "exists" or "grep") can't be overridden.
1355
1356 Autoloading
1357 If you call a subroutine that is undefined, you would ordinarily get an
1358 immediate, fatal error complaining that the subroutine doesn't exist.
1359 (Likewise for subroutines being used as methods, when the method
1360 doesn't exist in any base class of the class's package.) However, if
1361 an "AUTOLOAD" subroutine is defined in the package or packages used to
1362 locate the original subroutine, then that "AUTOLOAD" subroutine is
1363 called with the arguments that would have been passed to the original
1364 subroutine. The fully qualified name of the original subroutine
1365 magically appears in the global $AUTOLOAD variable of the same package
1366 as the "AUTOLOAD" routine. The name is not passed as an ordinary
1367 argument because, er, well, just because, that's why. (As an
1368 exception, a method call to a nonexistent "import" or "unimport" method
1369 is just skipped instead.)
1370
1371 Many "AUTOLOAD" routines load in a definition for the requested
1372 subroutine using eval(), then execute that subroutine using a special
1373 form of goto() that erases the stack frame of the "AUTOLOAD" routine
1374 without a trace. (See the source to the standard module documented in
1375 AutoLoader, for example.) But an "AUTOLOAD" routine can also just
1376 emulate the routine and never define it. For example, let's pretend
1377 that a function that wasn't defined should just invoke "system" with
1378 those arguments. All you'd do is:
1379
1380 sub AUTOLOAD {
1381 my $program = $AUTOLOAD;
1382 $program =~ s/.*:://;
1383 system($program, @_);
1384 }
1385 date();
1386 who('am', 'i');
1387 ls('-l');
1388
1389 In fact, if you predeclare functions you want to call that way, you
1390 don't even need parentheses:
1391
1392 use subs qw(date who ls);
1393 date;
1394 who "am", "i";
1395 ls '-l';
1396
1397 A more complete example of this is the standard Shell module, which can
1398 treat undefined subroutine calls as calls to external programs.
1399
1400 Mechanisms are available to help modules writers split their modules
1401 into autoloadable files. See the standard AutoLoader module described
1402 in AutoLoader and in AutoSplit, the standard SelfLoader modules in
1403 SelfLoader, and the document on adding C functions to Perl code in
1404 perlxs.
1405
1406 Subroutine Attributes
1407 A subroutine declaration or definition may have a list of attributes
1408 associated with it. If such an attribute list is present, it is broken
1409 up at space or colon boundaries and treated as though a "use
1410 attributes" had been seen. See attributes for details about what
1411 attributes are currently supported. Unlike the limitation with the
1412 obsolescent "use attrs", the "sub : ATTRLIST" syntax works to associate
1413 the attributes with a pre-declaration, and not just with a subroutine
1414 definition.
1415
1416 The attributes must be valid as simple identifier names (without any
1417 punctuation other than the '_' character). They may have a parameter
1418 list appended, which is only checked for whether its parentheses
1419 ('(',')') nest properly.
1420
1421 Examples of valid syntax (even though the attributes are unknown):
1422
1423 sub fnord (&\%) : switch(10,foo(7,3)) : expensive;
1424 sub plugh () : Ugly('\(") :Bad;
1425 sub xyzzy : _5x5 { ... }
1426
1427 Examples of invalid syntax:
1428
1429 sub fnord : switch(10,foo(); # ()-string not balanced
1430 sub snoid : Ugly('('); # ()-string not balanced
1431 sub xyzzy : 5x5; # "5x5" not a valid identifier
1432 sub plugh : Y2::north; # "Y2::north" not a simple identifier
1433 sub snurt : foo + bar; # "+" not a colon or space
1434
1435 The attribute list is passed as a list of constant strings to the code
1436 which associates them with the subroutine. In particular, the second
1437 example of valid syntax above currently looks like this in terms of how
1438 it's parsed and invoked:
1439
1440 use attributes __PACKAGE__, \&plugh, q[Ugly('\(")], 'Bad';
1441
1442 For further details on attribute lists and their manipulation, see
1443 attributes and Attribute::Handlers.
1444
1446 See "Function Templates" in perlref for more about references and
1447 closures. See perlxs if you'd like to learn about calling C
1448 subroutines from Perl. See perlembed if you'd like to learn about
1449 calling Perl subroutines from C. See perlmod to learn about bundling
1450 up your functions in separate files. See perlmodlib to learn what
1451 library modules come standard on your system. See perltoot to learn
1452 how to make object method calls.
1453
1454
1455
1456perl v5.12.4 2011-06-07 PERLSUB(1)