1PERLSUB(1)             Perl Programmers Reference Guide             PERLSUB(1)
2
3
4

NAME

6       perlsub - Perl subroutines
7

SYNOPSIS

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

DESCRIPTION

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           local ($cond ? $v1 : $v2);  # several types of lvalues support
511                                       # localization
512
513           # localization of symbols
514
515           local *FH;                  # localize $FH, @FH, %FH, &FH  ...
516           local *merlyn = *randal;    # now $merlyn is really $randal, plus
517                                       #     @merlyn is really @randal, etc
518           local *merlyn = 'randal';   # SAME THING: promote 'randal' to *randal
519           local *merlyn = \$randal;   # just alias $merlyn, not @merlyn etc
520
521       A "local" modifies its listed variables to be "local" to the enclosing
522       block, "eval", or "do FILE"--and to any subroutine called from within
523       that block.  A "local" just gives temporary values to global (meaning
524       package) variables.  It does not create a local variable.  This is
525       known as dynamic scoping.  Lexical scoping is done with "my", which
526       works more like C's auto declarations.
527
528       Some types of lvalues can be localized as well : hash and array
529       elements and slices, conditionals (provided that their result is always
530       localizable), and symbolic references.  As for simple variables, this
531       creates new, dynamically scoped values.
532
533       If more than one variable or expression is given to "local", they must
534       be placed in parentheses.  This operator works by saving the current
535       values of those variables in its argument list on a hidden stack and
536       restoring them upon exiting the block, subroutine, or eval.  This means
537       that called subroutines can also reference the local variable, but not
538       the global one.  The argument list may be assigned to if desired, which
539       allows you to initialize your local variables.  (If no initializer is
540       given for a particular variable, it is created with an undefined
541       value.)
542
543       Because "local" is a run-time operator, it gets executed each time
544       through a loop.  Consequently, it's more efficient to localize your
545       variables outside the loop.
546
547       Grammatical note on local()
548
549       A "local" is simply a modifier on an lvalue expression.  When you
550       assign to a "local"ized variable, the "local" doesn't change whether
551       its list is viewed as a scalar or an array.  So
552
553           local($foo) = <STDIN>;
554           local @FOO = <STDIN>;
555
556       both supply a list context to the right-hand side, while
557
558           local $foo = <STDIN>;
559
560       supplies a scalar context.
561
562       Localization of special variables
563
564       If you localize a special variable, you'll be giving a new value to it,
565       but its magic won't go away.  That means that all side-effects related
566       to this magic still work with the localized value.
567
568       This feature allows code like this to work :
569
570           # Read the whole contents of FILE in $slurp
571           { local $/ = undef; $slurp = <FILE>; }
572
573       Note, however, that this restricts localization of some values ; for
574       example, the following statement dies, as of perl 5.9.0, with an error
575       Modification of a read-only value attempted, because the $1 variable is
576       magical and read-only :
577
578           local $1 = 2;
579
580       Similarly, but in a way more difficult to spot, the following snippet
581       will die in perl 5.9.0 :
582
583           sub f { local $_ = "foo"; print }
584           for ($1) {
585               # now $_ is aliased to $1, thus is magic and readonly
586               f();
587           }
588
589       See next section for an alternative to this situation.
590
591       WARNING: Localization of tied arrays and hashes does not currently work
592       as described.  This will be fixed in a future release of Perl; in the
593       meantime, avoid code that relies on any particular behaviour of
594       localising tied arrays or hashes (localising individual elements is
595       still okay).  See "Localising Tied Arrays and Hashes Is Broken" in
596       perl58delta for more details.
597
598       Localization of globs
599
600       The construct
601
602           local *name;
603
604       creates a whole new symbol table entry for the glob "name" in the
605       current package.  That means that all variables in its glob slot
606       ($name, @name, %name, &name, and the "name" filehandle) are dynamically
607       reset.
608
609       This implies, among other things, that any magic eventually carried by
610       those variables is locally lost.  In other words, saying "local */"
611       will not have any effect on the internal value of the input record
612       separator.
613
614       Notably, if you want to work with a brand new value of the default
615       scalar $_, and avoid the potential problem listed above about $_
616       previously carrying a magic value, you should use "local *_" instead of
617       "local $_".  As of perl 5.9.1, you can also use the lexical form of $_
618       (declaring it with "my $_"), which avoids completely this problem.
619
620       Localization of elements of composite types
621
622       It's also worth taking a moment to explain what happens when you
623       "local"ize a member of a composite type (i.e. an array or hash
624       element).  In this case, the element is "local"ized by name. This means
625       that when the scope of the "local()" ends, the saved value will be
626       restored to the hash element whose key was named in the "local()", or
627       the array element whose index was named in the "local()".  If that
628       element was deleted while the "local()" was in effect (e.g. by a
629       "delete()" from a hash or a "shift()" of an array), it will spring back
630       into existence, possibly extending an array and filling in the skipped
631       elements with "undef".  For instance, if you say
632
633           %hash = ( 'This' => 'is', 'a' => 'test' );
634           @ary  = ( 0..5 );
635           {
636                local($ary[5]) = 6;
637                local($hash{'a'}) = 'drill';
638                while (my $e = pop(@ary)) {
639                    print "$e . . .\n";
640                    last unless $e > 3;
641                }
642                if (@ary) {
643                    $hash{'only a'} = 'test';
644                    delete $hash{'a'};
645                }
646           }
647           print join(' ', map { "$_ $hash{$_}" } sort keys %hash),".\n";
648           print "The array has ",scalar(@ary)," elements: ",
649                 join(', ', map { defined $_ ? $_ : 'undef' } @ary),"\n";
650
651       Perl will print
652
653           6 . . .
654           4 . . .
655           3 . . .
656           This is a test only a test.
657           The array has 6 elements: 0, 1, 2, undef, undef, 5
658
659       The behavior of local() on non-existent members of composite types is
660       subject to change in future.
661
662   Lvalue subroutines
663       WARNING: Lvalue subroutines are still experimental and the
664       implementation may change in future versions of Perl.
665
666       It is possible to return a modifiable value from a subroutine.  To do
667       this, you have to declare the subroutine to return an lvalue.
668
669           my $val;
670           sub canmod : lvalue {
671               # return $val; this doesn't work, don't say "return"
672               $val;
673           }
674           sub nomod {
675               $val;
676           }
677
678           canmod() = 5;   # assigns to $val
679           nomod()  = 5;   # ERROR
680
681       The scalar/list context for the subroutine and for the right-hand side
682       of assignment is determined as if the subroutine call is replaced by a
683       scalar. For example, consider:
684
685           data(2,3) = get_data(3,4);
686
687       Both subroutines here are called in a scalar context, while in:
688
689           (data(2,3)) = get_data(3,4);
690
691       and in:
692
693           (data(2),data(3)) = get_data(3,4);
694
695       all the subroutines are called in a list context.
696
697       Lvalue subroutines are EXPERIMENTAL
698           They appear to be convenient, but there are several reasons to be
699           circumspect.
700
701           You can't use the return keyword, you must pass out the value
702           before falling out of subroutine scope. (see comment in example
703           above).  This is usually not a problem, but it disallows an
704           explicit return out of a deeply nested loop, which is sometimes a
705           nice way out.
706
707           They violate encapsulation.  A normal mutator can check the
708           supplied argument before setting the attribute it is protecting, an
709           lvalue subroutine never gets that chance.  Consider;
710
711               my $some_array_ref = [];    # protected by mutators ??
712
713               sub set_arr {               # normal mutator
714                   my $val = shift;
715                   die("expected array, you supplied ", ref $val)
716                      unless ref $val eq 'ARRAY';
717                   $some_array_ref = $val;
718               }
719               sub set_arr_lv : lvalue {   # lvalue mutator
720                   $some_array_ref;
721               }
722
723               # set_arr_lv cannot stop this !
724               set_arr_lv() = { a => 1 };
725
726   Passing Symbol Table Entries (typeglobs)
727       WARNING: The mechanism described in this section was originally the
728       only way to simulate pass-by-reference in older versions of Perl.
729       While it still works fine in modern versions, the new reference
730       mechanism is generally easier to work with.  See below.
731
732       Sometimes you don't want to pass the value of an array to a subroutine
733       but rather the name of it, so that the subroutine can modify the global
734       copy of it rather than working with a local copy.  In perl you can
735       refer to all objects of a particular name by prefixing the name with a
736       star: *foo.  This is often known as a "typeglob", because the star on
737       the front can be thought of as a wildcard match for all the funny
738       prefix characters on variables and subroutines and such.
739
740       When evaluated, the typeglob produces a scalar value that represents
741       all the objects of that name, including any filehandle, format, or
742       subroutine.  When assigned to, it causes the name mentioned to refer to
743       whatever "*" value was assigned to it.  Example:
744
745           sub doubleary {
746               local(*someary) = @_;
747               foreach $elem (@someary) {
748                   $elem *= 2;
749               }
750           }
751           doubleary(*foo);
752           doubleary(*bar);
753
754       Scalars are already passed by reference, so you can modify scalar
755       arguments without using this mechanism by referring explicitly to $_[0]
756       etc.  You can modify all the elements of an array by passing all the
757       elements as scalars, but you have to use the "*" mechanism (or the
758       equivalent reference mechanism) to "push", "pop", or change the size of
759       an array.  It will certainly be faster to pass the typeglob (or
760       reference).
761
762       Even if you don't want to modify an array, this mechanism is useful for
763       passing multiple arrays in a single LIST, because normally the LIST
764       mechanism will merge all the array values so that you can't extract out
765       the individual arrays.  For more on typeglobs, see "Typeglobs and
766       Filehandles" in perldata.
767
768   When to Still Use local()
769       Despite the existence of "my", there are still three places where the
770       "local" operator still shines.  In fact, in these three places, you
771       must use "local" instead of "my".
772
773       1.  You need to give a global variable a temporary value, especially
774           $_.
775
776           The global variables, like @ARGV or the punctuation variables, must
777           be "local"ized with "local()".  This block reads in /etc/motd, and
778           splits it up into chunks separated by lines of equal signs, which
779           are placed in @Fields.
780
781               {
782                   local @ARGV = ("/etc/motd");
783                   local $/ = undef;
784                   local $_ = <>;
785                   @Fields = split /^\s*=+\s*$/;
786               }
787
788           It particular, it's important to "local"ize $_ in any routine that
789           assigns to it.  Look out for implicit assignments in "while"
790           conditionals.
791
792       2.  You need to create a local file or directory handle or a local
793           function.
794
795           A function that needs a filehandle of its own must use "local()" on
796           a complete typeglob.   This can be used to create new symbol table
797           entries:
798
799               sub ioqueue {
800                   local  (*READER, *WRITER);    # not my!
801                   pipe    (READER,  WRITER)     or die "pipe: $!";
802                   return (*READER, *WRITER);
803               }
804               ($head, $tail) = ioqueue();
805
806           See the Symbol module for a way to create anonymous symbol table
807           entries.
808
809           Because assignment of a reference to a typeglob creates an alias,
810           this can be used to create what is effectively a local function, or
811           at least, a local alias.
812
813               {
814                   local *grow = \&shrink; # only until this block exists
815                   grow();                 # really calls shrink()
816                   move();                 # if move() grow()s, it shrink()s too
817               }
818               grow();                     # get the real grow() again
819
820           See "Function Templates" in perlref for more about manipulating
821           functions by name in this way.
822
823       3.  You want to temporarily change just one element of an array or
824           hash.
825
826           You can "local"ize just one element of an aggregate.  Usually this
827           is done on dynamics:
828
829               {
830                   local $SIG{INT} = 'IGNORE';
831                   funct();                            # uninterruptible
832               }
833               # interruptibility automatically restored here
834
835           But it also works on lexically declared aggregates.  Prior to
836           5.005, this operation could on occasion misbehave.
837
838   Pass by Reference
839       If you want to pass more than one array or hash into a function--or
840       return them from it--and have them maintain their integrity, then
841       you're going to have to use an explicit pass-by-reference.  Before you
842       do that, you need to understand references as detailed in perlref.
843       This section may not make much sense to you otherwise.
844
845       Here are a few simple examples.  First, let's pass in several arrays to
846       a function and have it "pop" all of then, returning a new list of all
847       their former last elements:
848
849           @tailings = popmany ( \@a, \@b, \@c, \@d );
850
851           sub popmany {
852               my $aref;
853               my @retlist = ();
854               foreach $aref ( @_ ) {
855                   push @retlist, pop @$aref;
856               }
857               return @retlist;
858           }
859
860       Here's how you might write a function that returns a list of keys
861       occurring in all the hashes passed to it:
862
863           @common = inter( \%foo, \%bar, \%joe );
864           sub inter {
865               my ($k, $href, %seen); # locals
866               foreach $href (@_) {
867                   while ( $k = each %$href ) {
868                       $seen{$k}++;
869                   }
870               }
871               return grep { $seen{$_} == @_ } keys %seen;
872           }
873
874       So far, we're using just the normal list return mechanism.  What
875       happens if you want to pass or return a hash?  Well, if you're using
876       only one of them, or you don't mind them concatenating, then the normal
877       calling convention is ok, although a little expensive.
878
879       Where people get into trouble is here:
880
881           (@a, @b) = func(@c, @d);
882       or
883           (%a, %b) = func(%c, %d);
884
885       That syntax simply won't work.  It sets just @a or %a and clears the @b
886       or %b.  Plus the function didn't get passed into two separate arrays or
887       hashes: it got one long list in @_, as always.
888
889       If you can arrange for everyone to deal with this through references,
890       it's cleaner code, although not so nice to look at.  Here's a function
891       that takes two array references as arguments, returning the two array
892       elements in order of how many elements they have in them:
893
894           ($aref, $bref) = func(\@c, \@d);
895           print "@$aref has more than @$bref\n";
896           sub func {
897               my ($cref, $dref) = @_;
898               if (@$cref > @$dref) {
899                   return ($cref, $dref);
900               } else {
901                   return ($dref, $cref);
902               }
903           }
904
905       It turns out that you can actually do this also:
906
907           (*a, *b) = func(\@c, \@d);
908           print "@a has more than @b\n";
909           sub func {
910               local (*c, *d) = @_;
911               if (@c > @d) {
912                   return (\@c, \@d);
913               } else {
914                   return (\@d, \@c);
915               }
916           }
917
918       Here we're using the typeglobs to do symbol table aliasing.  It's a tad
919       subtle, though, and also won't work if you're using "my" variables,
920       because only globals (even in disguise as "local"s) are in the symbol
921       table.
922
923       If you're passing around filehandles, you could usually just use the
924       bare typeglob, like *STDOUT, but typeglobs references work, too.  For
925       example:
926
927           splutter(\*STDOUT);
928           sub splutter {
929               my $fh = shift;
930               print $fh "her um well a hmmm\n";
931           }
932
933           $rec = get_rec(\*STDIN);
934           sub get_rec {
935               my $fh = shift;
936               return scalar <$fh>;
937           }
938
939       If you're planning on generating new filehandles, you could do this.
940       Notice to pass back just the bare *FH, not its reference.
941
942           sub openit {
943               my $path = shift;
944               local *FH;
945               return open (FH, $path) ? *FH : undef;
946           }
947
948   Prototypes
949       Perl supports a very limited kind of compile-time argument checking
950       using function prototyping.  If you declare
951
952           sub mypush (\@@)
953
954       then "mypush()" takes arguments exactly like "push()" does.  The
955       function declaration must be visible at compile time.  The prototype
956       affects only interpretation of new-style calls to the function, where
957       new-style is defined as not using the "&" character.  In other words,
958       if you call it like a built-in function, then it behaves like a built-
959       in function.  If you call it like an old-fashioned subroutine, then it
960       behaves like an old-fashioned subroutine.  It naturally falls out from
961       this rule that prototypes have no influence on subroutine references
962       like "\&foo" or on indirect subroutine calls like "&{$subref}" or
963       "$subref->()".
964
965       Method calls are not influenced by prototypes either, because the
966       function to be called is indeterminate at compile time, since the exact
967       code called depends on inheritance.
968
969       Because the intent of this feature is primarily to let you define
970       subroutines that work like built-in functions, here are prototypes for
971       some other functions that parse almost exactly like the corresponding
972       built-in.
973
974           Declared as                 Called as
975
976           sub mylink ($$)          mylink $old, $new
977           sub myvec ($$$)          myvec $var, $offset, 1
978           sub myindex ($$;$)       myindex &getstring, "substr"
979           sub mysyswrite ($$$;$)   mysyswrite $buf, 0, length($buf) - $off, $off
980           sub myreverse (@)        myreverse $a, $b, $c
981           sub myjoin ($@)          myjoin ":", $a, $b, $c
982           sub mypop (\@)           mypop @array
983           sub mysplice (\@$$@)     mysplice @array, 0, 2, @pushme
984           sub mykeys (\%)          mykeys %{$hashref}
985           sub myopen (*;$)         myopen HANDLE, $name
986           sub mypipe (**)          mypipe READHANDLE, WRITEHANDLE
987           sub mygrep (&@)          mygrep { /foo/ } $a, $b, $c
988           sub myrand (;$)          myrand 42
989           sub mytime ()            mytime
990
991       Any backslashed prototype character represents an actual argument that
992       absolutely must start with that character.  The value passed as part of
993       @_ will be a reference to the actual argument given in the subroutine
994       call, obtained by applying "\" to that argument.
995
996       You can also backslash several argument types simultaneously by using
997       the "\[]" notation:
998
999           sub myref (\[$@%&*])
1000
1001       will allow calling myref() as
1002
1003           myref $var
1004           myref @array
1005           myref %hash
1006           myref &sub
1007           myref *glob
1008
1009       and the first argument of myref() will be a reference to a scalar, an
1010       array, a hash, a code, or a glob.
1011
1012       Unbackslashed prototype characters have special meanings.  Any
1013       unbackslashed "@" or "%" eats all remaining arguments, and forces list
1014       context.  An argument represented by "$" forces scalar context.  An "&"
1015       requires an anonymous subroutine, which, if passed as the first
1016       argument, does not require the "sub" keyword or a subsequent comma.
1017
1018       A "*" allows the subroutine to accept a bareword, constant, scalar
1019       expression, typeglob, or a reference to a typeglob in that slot.  The
1020       value will be available to the subroutine either as a simple scalar, or
1021       (in the latter two cases) as a reference to the typeglob.  If you wish
1022       to always convert such arguments to a typeglob reference, use
1023       Symbol::qualify_to_ref() as follows:
1024
1025           use Symbol 'qualify_to_ref';
1026
1027           sub foo (*) {
1028               my $fh = qualify_to_ref(shift, caller);
1029               ...
1030           }
1031
1032       A semicolon (";") separates mandatory arguments from optional
1033       arguments.  It is redundant before "@" or "%", which gobble up
1034       everything else.
1035
1036       As the last character of a prototype, or just before a semicolon, you
1037       can use "_" in place of "$": if this argument is not provided, $_ will
1038       be used instead.
1039
1040       Note how the last three examples in the table above are treated
1041       specially by the parser.  "mygrep()" is parsed as a true list operator,
1042       "myrand()" is parsed as a true unary operator with unary precedence the
1043       same as "rand()", and "mytime()" is truly without arguments, just like
1044       "time()".  That is, if you say
1045
1046           mytime +2;
1047
1048       you'll get "mytime() + 2", not mytime(2), which is how it would be
1049       parsed without a prototype.
1050
1051       The interesting thing about "&" is that you can generate new syntax
1052       with it, provided it's in the initial position:
1053
1054           sub try (&@) {
1055               my($try,$catch) = @_;
1056               eval { &$try };
1057               if ($@) {
1058                   local $_ = $@;
1059                   &$catch;
1060               }
1061           }
1062           sub catch (&) { $_[0] }
1063
1064           try {
1065               die "phooey";
1066           } catch {
1067               /phooey/ and print "unphooey\n";
1068           };
1069
1070       That prints "unphooey".  (Yes, there are still unresolved issues having
1071       to do with visibility of @_.  I'm ignoring that question for the
1072       moment.  (But note that if we make @_ lexically scoped, those anonymous
1073       subroutines can act like closures... (Gee, is this sounding a little
1074       Lispish?  (Never mind.))))
1075
1076       And here's a reimplementation of the Perl "grep" operator:
1077
1078           sub mygrep (&@) {
1079               my $code = shift;
1080               my @result;
1081               foreach $_ (@_) {
1082                   push(@result, $_) if &$code;
1083               }
1084               @result;
1085           }
1086
1087       Some folks would prefer full alphanumeric prototypes.  Alphanumerics
1088       have been intentionally left out of prototypes for the express purpose
1089       of someday in the future adding named, formal parameters.  The current
1090       mechanism's main goal is to let module writers provide better
1091       diagnostics for module users.  Larry feels the notation quite
1092       understandable to Perl programmers, and that it will not intrude
1093       greatly upon the meat of the module, nor make it harder to read.  The
1094       line noise is visually encapsulated into a small pill that's easy to
1095       swallow.
1096
1097       If you try to use an alphanumeric sequence in a prototype you will
1098       generate an optional warning - "Illegal character in prototype...".
1099       Unfortunately earlier versions of Perl allowed the prototype to be used
1100       as long as its prefix was a valid prototype.  The warning may be
1101       upgraded to a fatal error in a future version of Perl once the majority
1102       of offending code is fixed.
1103
1104       It's probably best to prototype new functions, not retrofit prototyping
1105       into older ones.  That's because you must be especially careful about
1106       silent impositions of differing list versus scalar contexts.  For
1107       example, if you decide that a function should take just one parameter,
1108       like this:
1109
1110           sub func ($) {
1111               my $n = shift;
1112               print "you gave me $n\n";
1113           }
1114
1115       and someone has been calling it with an array or expression returning a
1116       list:
1117
1118           func(@foo);
1119           func( split /:/ );
1120
1121       Then you've just supplied an automatic "scalar" in front of their
1122       argument, which can be more than a bit surprising.  The old @foo which
1123       used to hold one thing doesn't get passed in.  Instead, "func()" now
1124       gets passed in a 1; that is, the number of elements in @foo.  And the
1125       "split" gets called in scalar context so it starts scribbling on your
1126       @_ parameter list.  Ouch!
1127
1128       This is all very powerful, of course, and should be used only in
1129       moderation to make the world a better place.
1130
1131   Constant Functions
1132       Functions with a prototype of "()" are potential candidates for
1133       inlining.  If the result after optimization and constant folding is
1134       either a constant or a lexically-scoped scalar which has no other
1135       references, then it will be used in place of function calls made
1136       without "&".  Calls made using "&" are never inlined.  (See constant.pm
1137       for an easy way to declare most constants.)
1138
1139       The following functions would all be inlined:
1140
1141           sub pi ()           { 3.14159 }             # Not exact, but close.
1142           sub PI ()           { 4 * atan2 1, 1 }      # As good as it gets,
1143                                                       # and it's inlined, too!
1144           sub ST_DEV ()       { 0 }
1145           sub ST_INO ()       { 1 }
1146
1147           sub FLAG_FOO ()     { 1 << 8 }
1148           sub FLAG_BAR ()     { 1 << 9 }
1149           sub FLAG_MASK ()    { FLAG_FOO | FLAG_BAR }
1150
1151           sub OPT_BAZ ()      { not (0x1B58 & FLAG_MASK) }
1152
1153           sub N () { int(OPT_BAZ) / 3 }
1154
1155           sub FOO_SET () { 1 if FLAG_MASK & FLAG_FOO }
1156
1157       Be aware that these will not be inlined; as they contain inner scopes,
1158       the constant folding doesn't reduce them to a single constant:
1159
1160           sub foo_set () { if (FLAG_MASK & FLAG_FOO) { 1 } }
1161
1162           sub baz_val () {
1163               if (OPT_BAZ) {
1164                   return 23;
1165               }
1166               else {
1167                   return 42;
1168               }
1169           }
1170
1171       If you redefine a subroutine that was eligible for inlining, you'll get
1172       a mandatory warning.  (You can use this warning to tell whether or not
1173       a particular subroutine is considered constant.)  The warning is
1174       considered severe enough not to be optional because previously compiled
1175       invocations of the function will still be using the old value of the
1176       function.  If you need to be able to redefine the subroutine, you need
1177       to ensure that it isn't inlined, either by dropping the "()" prototype
1178       (which changes calling semantics, so beware) or by thwarting the
1179       inlining mechanism in some other way, such as
1180
1181           sub not_inlined () {
1182               23 if $];
1183           }
1184
1185   Overriding Built-in Functions
1186       Many built-in functions may be overridden, though this should be tried
1187       only occasionally and for good reason.  Typically this might be done by
1188       a package attempting to emulate missing built-in functionality on a
1189       non-Unix system.
1190
1191       Overriding may be done only by importing the name from a module at
1192       compile time--ordinary predeclaration isn't good enough.  However, the
1193       "use subs" pragma lets you, in effect, predeclare subs via the import
1194       syntax, and these names may then override built-in ones:
1195
1196           use subs 'chdir', 'chroot', 'chmod', 'chown';
1197           chdir $somewhere;
1198           sub chdir { ... }
1199
1200       To unambiguously refer to the built-in form, precede the built-in name
1201       with the special package qualifier "CORE::".  For example, saying
1202       "CORE::open()" always refers to the built-in "open()", even if the
1203       current package has imported some other subroutine called "&open()"
1204       from elsewhere.  Even though it looks like a regular function call, it
1205       isn't: you can't take a reference to it, such as the incorrect
1206       "\&CORE::open" might appear to produce.
1207
1208       Library modules should not in general export built-in names like "open"
1209       or "chdir" as part of their default @EXPORT list, because these may
1210       sneak into someone else's namespace and change the semantics
1211       unexpectedly.  Instead, if the module adds that name to @EXPORT_OK,
1212       then it's possible for a user to import the name explicitly, but not
1213       implicitly.  That is, they could say
1214
1215           use Module 'open';
1216
1217       and it would import the "open" override.  But if they said
1218
1219           use Module;
1220
1221       they would get the default imports without overrides.
1222
1223       The foregoing mechanism for overriding built-in is restricted, quite
1224       deliberately, to the package that requests the import.  There is a
1225       second method that is sometimes applicable when you wish to override a
1226       built-in everywhere, without regard to namespace boundaries.  This is
1227       achieved by importing a sub into the special namespace
1228       "CORE::GLOBAL::".  Here is an example that quite brazenly replaces the
1229       "glob" operator with something that understands regular expressions.
1230
1231           package REGlob;
1232           require Exporter;
1233           @ISA = 'Exporter';
1234           @EXPORT_OK = 'glob';
1235
1236           sub import {
1237               my $pkg = shift;
1238               return unless @_;
1239               my $sym = shift;
1240               my $where = ($sym =~ s/^GLOBAL_// ? 'CORE::GLOBAL' : caller(0));
1241               $pkg->export($where, $sym, @_);
1242           }
1243
1244           sub glob {
1245               my $pat = shift;
1246               my @got;
1247               if (opendir my $d, '.') {
1248                   @got = grep /$pat/, readdir $d;
1249                   closedir $d;
1250               }
1251               return @got;
1252           }
1253           1;
1254
1255       And here's how it could be (ab)used:
1256
1257           #use REGlob 'GLOBAL_glob';      # override glob() in ALL namespaces
1258           package Foo;
1259           use REGlob 'glob';              # override glob() in Foo:: only
1260           print for <^[a-z_]+\.pm\$>;     # show all pragmatic modules
1261
1262       The initial comment shows a contrived, even dangerous example.  By
1263       overriding "glob" globally, you would be forcing the new (and
1264       subversive) behavior for the "glob" operator for every namespace,
1265       without the complete cognizance or cooperation of the modules that own
1266       those namespaces.  Naturally, this should be done with extreme
1267       caution--if it must be done at all.
1268
1269       The "REGlob" example above does not implement all the support needed to
1270       cleanly override perl's "glob" operator.  The built-in "glob" has
1271       different behaviors depending on whether it appears in a scalar or list
1272       context, but our "REGlob" doesn't.  Indeed, many perl built-in have
1273       such context sensitive behaviors, and these must be adequately
1274       supported by a properly written override.  For a fully functional
1275       example of overriding "glob", study the implementation of
1276       "File::DosGlob" in the standard library.
1277
1278       When you override a built-in, your replacement should be consistent (if
1279       possible) with the built-in native syntax.  You can achieve this by
1280       using a suitable prototype.  To get the prototype of an overridable
1281       built-in, use the "prototype" function with an argument of
1282       "CORE::builtin_name" (see "prototype" in perlfunc).
1283
1284       Note however that some built-ins can't have their syntax expressed by a
1285       prototype (such as "system" or "chomp").  If you override them you
1286       won't be able to fully mimic their original syntax.
1287
1288       The built-ins "do", "require" and "glob" can also be overridden, but
1289       due to special magic, their original syntax is preserved, and you don't
1290       have to define a prototype for their replacements.  (You can't override
1291       the "do BLOCK" syntax, though).
1292
1293       "require" has special additional dark magic: if you invoke your
1294       "require" replacement as "require Foo::Bar", it will actually receive
1295       the argument "Foo/Bar.pm" in @_.  See "require" in perlfunc.
1296
1297       And, as you'll have noticed from the previous example, if you override
1298       "glob", the "<*>" glob operator is overridden as well.
1299
1300       In a similar fashion, overriding the "readline" function also overrides
1301       the equivalent I/O operator "<FILEHANDLE>". Also, overriding "readpipe"
1302       also overrides the operators "``" and "qx//".
1303
1304       Finally, some built-ins (e.g. "exists" or "grep") can't be overridden.
1305
1306   Autoloading
1307       If you call a subroutine that is undefined, you would ordinarily get an
1308       immediate, fatal error complaining that the subroutine doesn't exist.
1309       (Likewise for subroutines being used as methods, when the method
1310       doesn't exist in any base class of the class's package.)  However, if
1311       an "AUTOLOAD" subroutine is defined in the package or packages used to
1312       locate the original subroutine, then that "AUTOLOAD" subroutine is
1313       called with the arguments that would have been passed to the original
1314       subroutine.  The fully qualified name of the original subroutine
1315       magically appears in the global $AUTOLOAD variable of the same package
1316       as the "AUTOLOAD" routine.  The name is not passed as an ordinary
1317       argument because, er, well, just because, that's why.  (As an
1318       exception, a method call to a nonexistent "import" or "unimport" method
1319       is just skipped instead.)
1320
1321       Many "AUTOLOAD" routines load in a definition for the requested
1322       subroutine using eval(), then execute that subroutine using a special
1323       form of goto() that erases the stack frame of the "AUTOLOAD" routine
1324       without a trace.  (See the source to the standard module documented in
1325       AutoLoader, for example.)  But an "AUTOLOAD" routine can also just
1326       emulate the routine and never define it.   For example, let's pretend
1327       that a function that wasn't defined should just invoke "system" with
1328       those arguments.  All you'd do is:
1329
1330           sub AUTOLOAD {
1331               my $program = $AUTOLOAD;
1332               $program =~ s/.*:://;
1333               system($program, @_);
1334           }
1335           date();
1336           who('am', 'i');
1337           ls('-l');
1338
1339       In fact, if you predeclare functions you want to call that way, you
1340       don't even need parentheses:
1341
1342           use subs qw(date who ls);
1343           date;
1344           who "am", "i";
1345           ls '-l';
1346
1347       A more complete example of this is the standard Shell module, which can
1348       treat undefined subroutine calls as calls to external programs.
1349
1350       Mechanisms are available to help modules writers split their modules
1351       into autoloadable files.  See the standard AutoLoader module described
1352       in AutoLoader and in AutoSplit, the standard SelfLoader modules in
1353       SelfLoader, and the document on adding C functions to Perl code in
1354       perlxs.
1355
1356   Subroutine Attributes
1357       A subroutine declaration or definition may have a list of attributes
1358       associated with it.  If such an attribute list is present, it is broken
1359       up at space or colon boundaries and treated as though a "use
1360       attributes" had been seen.  See attributes for details about what
1361       attributes are currently supported.  Unlike the limitation with the
1362       obsolescent "use attrs", the "sub : ATTRLIST" syntax works to associate
1363       the attributes with a pre-declaration, and not just with a subroutine
1364       definition.
1365
1366       The attributes must be valid as simple identifier names (without any
1367       punctuation other than the '_' character).  They may have a parameter
1368       list appended, which is only checked for whether its parentheses
1369       ('(',')') nest properly.
1370
1371       Examples of valid syntax (even though the attributes are unknown):
1372
1373           sub fnord (&\%) : switch(10,foo(7,3))  :  expensive;
1374           sub plugh () : Ugly('\(") :Bad;
1375           sub xyzzy : _5x5 { ... }
1376
1377       Examples of invalid syntax:
1378
1379           sub fnord : switch(10,foo(); # ()-string not balanced
1380           sub snoid : Ugly('(');        # ()-string not balanced
1381           sub xyzzy : 5x5;              # "5x5" not a valid identifier
1382           sub plugh : Y2::north;        # "Y2::north" not a simple identifier
1383           sub snurt : foo + bar;        # "+" not a colon or space
1384
1385       The attribute list is passed as a list of constant strings to the code
1386       which associates them with the subroutine.  In particular, the second
1387       example of valid syntax above currently looks like this in terms of how
1388       it's parsed and invoked:
1389
1390           use attributes __PACKAGE__, \&plugh, q[Ugly('\(")], 'Bad';
1391
1392       For further details on attribute lists and their manipulation, see
1393       attributes and Attribute::Handlers.
1394

SEE ALSO

1396       See "Function Templates" in perlref for more about references and
1397       closures.  See perlxs if you'd like to learn about calling C
1398       subroutines from Perl.  See perlembed if you'd like to learn about
1399       calling Perl subroutines from C.  See perlmod to learn about bundling
1400       up your functions in separate files.  See perlmodlib to learn what
1401       library modules come standard on your system.  See perltoot to learn
1402       how to make object method calls.
1403
1404
1405
1406perl v5.10.1                      2009-02-12                        PERLSUB(1)
Impressum