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

SEE ALSO

1367       See "Function Templates" in perlref for more about references and clo‐
1368       sures.  See perlxs if you'd like to learn about calling C subroutines
1369       from Perl.  See perlembed if you'd like to learn about calling Perl
1370       subroutines from C.  See perlmod to learn about bundling up your func‐
1371       tions in separate files.  See perlmodlib to learn what library modules
1372       come standard on your system.  See perltoot to learn how to make object
1373       method calls.
1374
1375
1376
1377perl v5.8.8                       2006-01-07                        PERLSUB(1)
Impressum