This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
describe current behavior on local($foo{nothere}) (suggested by
[perl5.git] / pod / perlsub.pod
1 =head1 NAME
2
3 perlsub - Perl subroutines
4
5 =head1 SYNOPSIS
6
7 To declare subroutines:
8
9     sub NAME;             # A "forward" declaration.
10     sub NAME(PROTO);      #  ditto, but with prototypes
11
12     sub NAME BLOCK        # A declaration and a definition.
13     sub NAME(PROTO) BLOCK #  ditto, but with prototypes
14
15 To define an anonymous subroutine at runtime:
16
17     $subref = sub BLOCK;            # no proto
18     $subref = sub (PROTO) BLOCK;    # with proto
19
20 To import subroutines:
21
22     use PACKAGE qw(NAME1 NAME2 NAME3);
23
24 To call subroutines:
25
26     NAME(LIST);    # & is optional with parentheses.
27     NAME LIST;     # Parentheses optional if predeclared/imported.
28     &NAME;         # Makes current @_ visible to called subroutine.
29
30 =head1 DESCRIPTION
31
32 Like many languages, Perl provides for user-defined subroutines.  These
33 may be located anywhere in the main program, loaded in from other files
34 via the C<do>, C<require>, or C<use> keywords, or even generated on the
35 fly using C<eval> or anonymous subroutines (closures).  You can even call
36 a function indirectly using a variable containing its name or a CODE reference
37 to it.
38
39 The Perl model for function call and return values is simple: all
40 functions are passed as parameters one single flat list of scalars, and
41 all functions likewise return to their caller one single flat list of
42 scalars.  Any arrays or hashes in these call and return lists will
43 collapse, losing their identities--but you may always use
44 pass-by-reference instead to avoid this.  Both call and return lists may
45 contain as many or as few scalar elements as you'd like.  (Often a
46 function without an explicit return statement is called a subroutine, but
47 there's really no difference from the language's perspective.)
48
49 Any arguments passed to the routine come in as the array C<@_>.  Thus if you
50 called a function with two arguments, those would be stored in C<$_[0]>
51 and C<$_[1]>.  The array C<@_> is a local array, but its elements are
52 aliases for the actual scalar parameters.  In particular, if an element
53 C<$_[0]> is updated, the corresponding argument is updated (or an error
54 occurs if it is not updatable).  If an argument is an array or hash
55 element which did not exist when the function was called, that element is
56 created only when (and if) it is modified or if a reference to it is
57 taken.  (Some earlier versions of Perl created the element whether or not
58 it was assigned to.)  Note that assigning to the whole array C<@_> removes
59 the aliasing, and does not update any arguments.
60
61 The return value of the subroutine is the value of the last expression
62 evaluated.  Alternatively, a C<return> statement may be used to exit the
63 subroutine, optionally specifying the returned value, which will be
64 evaluated in the appropriate context (list, scalar, or void) depending
65 on the context of the subroutine call.  If you specify no return value,
66 the subroutine will return an empty list in a list context, an undefined
67 value in a scalar context, or nothing in a void context.  If you return
68 one or more arrays and/or hashes, these will be flattened together into
69 one large indistinguishable list.
70
71 Perl does not have named formal parameters, but in practice all you do is
72 assign to a C<my()> list of these.  Any variables you use in the function
73 that aren't declared private are global variables.  For the gory details
74 on creating private variables, see
75 L<"Private Variables via my()"> and L<"Temporary Values via local()">.
76 To create protected environments for a set of functions in a separate
77 package (and probably a separate file), see L<perlmod/"Packages">.
78
79 Example:
80
81     sub max {
82         my $max = shift(@_);
83         foreach $foo (@_) {
84             $max = $foo if $max < $foo;
85         }
86         return $max;
87     }
88     $bestday = max($mon,$tue,$wed,$thu,$fri);
89
90 Example:
91
92     # get a line, combining continuation lines
93     #  that start with whitespace
94
95     sub get_line {
96         $thisline = $lookahead;  # GLOBAL VARIABLES!!
97         LINE: while (defined($lookahead = <STDIN>)) {
98             if ($lookahead =~ /^[ \t]/) {
99                 $thisline .= $lookahead;
100             }
101             else {
102                 last LINE;
103             }
104         }
105         $thisline;
106     }
107
108     $lookahead = <STDIN>;       # get first line
109     while ($_ = get_line()) {
110         ...
111     }
112
113 Use array assignment to a local list to name your formal arguments:
114
115     sub maybeset {
116         my($key, $value) = @_;
117         $Foo{$key} = $value unless $Foo{$key};
118     }
119
120 This also has the effect of turning call-by-reference into call-by-value,
121 because the assignment copies the values.  Otherwise a function is free to
122 do in-place modifications of C<@_> and change its caller's values.
123
124     upcase_in($v1, $v2);  # this changes $v1 and $v2
125     sub upcase_in {
126         for (@_) { tr/a-z/A-Z/ }
127     }
128
129 You aren't allowed to modify constants in this way, of course.  If an
130 argument were actually literal and you tried to change it, you'd take a
131 (presumably fatal) exception.   For example, this won't work:
132
133     upcase_in("frederick");
134
135 It would be much safer if the C<upcase_in()> function
136 were written to return a copy of its parameters instead
137 of changing them in place:
138
139     ($v3, $v4) = upcase($v1, $v2);  # this doesn't
140     sub upcase {
141         return unless defined wantarray;  # void context, do nothing
142         my @parms = @_;
143         for (@parms) { tr/a-z/A-Z/ }
144         return wantarray ? @parms : $parms[0];
145     }
146
147 Notice how this (unprototyped) function doesn't care whether it was passed
148 real scalars or arrays.  Perl will see everything as one big long flat C<@_>
149 parameter list.  This is one of the ways where Perl's simple
150 argument-passing style shines.  The C<upcase()> function would work perfectly
151 well without changing the C<upcase()> definition even if we fed it things
152 like this:
153
154     @newlist   = upcase(@list1, @list2);
155     @newlist   = upcase( split /:/, $var );
156
157 Do not, however, be tempted to do this:
158
159     (@a, @b)   = upcase(@list1, @list2);
160
161 Because like its flat incoming parameter list, the return list is also
162 flat.  So all you have managed to do here is stored everything in C<@a> and
163 made C<@b> an empty list.  See L<Pass by Reference> for alternatives.
164
165 A subroutine may be called using the "C<&>" prefix.  The "C<&>" is optional
166 in modern Perls, and so are the parentheses if the subroutine has been
167 predeclared.  (Note, however, that the "C<&>" is I<NOT> optional when
168 you're just naming the subroutine, such as when it's used as an
169 argument to C<defined()> or C<undef()>.  Nor is it optional when you want to
170 do an indirect subroutine call with a subroutine name or reference
171 using the C<&$subref()> or C<&{$subref}()> constructs.  See L<perlref>
172 for more on that.)
173
174 Subroutines may be called recursively.  If a subroutine is called using
175 the "C<&>" form, the argument list is optional, and if omitted, no C<@_> array is
176 set up for the subroutine: the C<@_> array at the time of the call is
177 visible to subroutine instead.  This is an efficiency mechanism that
178 new users may wish to avoid.
179
180     &foo(1,2,3);        # pass three arguments
181     foo(1,2,3);         # the same
182
183     foo();              # pass a null list
184     &foo();             # the same
185
186     &foo;               # foo() get current args, like foo(@_) !!
187     foo;                # like foo() IFF sub foo predeclared, else "foo"
188
189 Not only does the "C<&>" form make the argument list optional, but it also
190 disables any prototype checking on the arguments you do provide.  This
191 is partly for historical reasons, and partly for having a convenient way
192 to cheat if you know what you're doing.  See the section on Prototypes below.
193
194 Function whose names are in all upper case are reserved to the Perl core,
195 just as are modules whose names are in all lower case.  A function in
196 all capitals is a loosely-held convention meaning it will be called
197 indirectly by the run-time system itself.  Functions that do special,
198 pre-defined things are C<BEGIN>, C<END>, C<AUTOLOAD>, and C<DESTROY>--plus all the
199 functions mentioned in L<perltie>.  The 5.005 release adds C<INIT>
200 to this list.
201
202 =head2 Private Variables via my()
203
204 Synopsis:
205
206     my $foo;            # declare $foo lexically local
207     my (@wid, %get);    # declare list of variables local
208     my $foo = "flurp";  # declare $foo lexical, and init it
209     my @oof = @bar;     # declare @oof lexical, and init it
210
211 A "C<my>" declares the listed variables to be confined (lexically) to the
212 enclosing block, conditional (C<if/unless/elsif/else>), loop
213 (C<for/foreach/while/until/continue>), subroutine, C<eval>, or
214 C<do/require/use>'d file.  If more than one value is listed, the list
215 must be placed in parentheses.  All listed elements must be legal lvalues.
216 Only alphanumeric identifiers may be lexically scoped--magical
217 builtins like C<$/> must currently be C<local>ize with "C<local>" instead.
218
219 Unlike dynamic variables created by the "C<local>" operator, lexical
220 variables declared with "C<my>" are totally hidden from the outside world,
221 including any called subroutines (even if it's the same subroutine called
222 from itself or elsewhere--every call gets its own copy).
223
224 This doesn't mean that a C<my()> variable declared in a statically
225 I<enclosing> lexical scope would be invisible.  Only the dynamic scopes
226 are cut off.   For example, the C<bumpx()> function below has access to the
227 lexical C<$x> variable because both the my and the sub occurred at the same
228 scope, presumably the file scope.
229
230     my $x = 10;
231     sub bumpx { $x++ } 
232
233 (An C<eval()>, however, can see the lexical variables of the scope it is
234 being evaluated in so long as the names aren't hidden by declarations within
235 the C<eval()> itself.  See L<perlref>.)
236
237 The parameter list to C<my()> may be assigned to if desired, which allows you
238 to initialize your variables.  (If no initializer is given for a
239 particular variable, it is created with the undefined value.)  Commonly
240 this is used to name the parameters to a subroutine.  Examples:
241
242     $arg = "fred";        # "global" variable
243     $n = cube_root(27);
244     print "$arg thinks the root is $n\n";
245  fred thinks the root is 3
246
247     sub cube_root {
248         my $arg = shift;  # name doesn't matter
249         $arg **= 1/3;
250         return $arg;
251     }
252
253 The "C<my>" is simply a modifier on something you might assign to.  So when
254 you do assign to the variables in its argument list, the "C<my>" doesn't
255 change whether those variables are viewed as a scalar or an array.  So
256
257     my ($foo) = <STDIN>;                # WRONG?
258     my @FOO = <STDIN>;
259
260 both supply a list context to the right-hand side, while
261
262     my $foo = <STDIN>;
263
264 supplies a scalar context.  But the following declares only one variable:
265
266     my $foo, $bar = 1;                  # WRONG
267
268 That has the same effect as
269
270     my $foo;
271     $bar = 1;
272
273 The declared variable is not introduced (is not visible) until after
274 the current statement.  Thus,
275
276     my $x = $x;
277
278 can be used to initialize the new $x with the value of the old C<$x>, and
279 the expression
280
281     my $x = 123 and $x == 123
282
283 is false unless the old C<$x> happened to have the value C<123>.
284
285 Lexical scopes of control structures are not bounded precisely by the
286 braces that delimit their controlled blocks; control expressions are
287 part of the scope, too.  Thus in the loop
288
289     while (defined(my $line = <>)) {
290         $line = lc $line;
291     } continue {
292         print $line;
293     }
294
295 the scope of C<$line> extends from its declaration throughout the rest of
296 the loop construct (including the C<continue> clause), but not beyond
297 it.  Similarly, in the conditional
298
299     if ((my $answer = <STDIN>) =~ /^yes$/i) {
300         user_agrees();
301     } elsif ($answer =~ /^no$/i) {
302         user_disagrees();
303     } else {
304         chomp $answer;
305         die "'$answer' is neither 'yes' nor 'no'";
306     }
307
308 the scope of C<$answer> extends from its declaration throughout the rest
309 of the conditional (including C<elsif> and C<else> clauses, if any),
310 but not beyond it.
311
312 (None of the foregoing applies to C<if/unless> or C<while/until>
313 modifiers appended to simple statements.  Such modifiers are not
314 control structures and have no effect on scoping.)
315
316 The C<foreach> loop defaults to scoping its index variable dynamically
317 (in the manner of C<local>; see below).  However, if the index
318 variable is prefixed with the keyword "C<my>", then it is lexically
319 scoped instead.  Thus in the loop
320
321     for my $i (1, 2, 3) {
322         some_function();
323     }
324
325 the scope of C<$i> extends to the end of the loop, but not beyond it, and
326 so the value of C<$i> is unavailable in C<some_function()>.
327
328 Some users may wish to encourage the use of lexically scoped variables.
329 As an aid to catching implicit references to package variables,
330 if you say
331
332     use strict 'vars';
333
334 then any variable reference from there to the end of the enclosing
335 block must either refer to a lexical variable, or must be fully
336 qualified with the package name.  A compilation error results
337 otherwise.  An inner block may countermand this with S<"C<no strict 'vars'>">.
338
339 A C<my()> has both a compile-time and a run-time effect.  At compile time,
340 the compiler takes notice of it; the principle usefulness of this is to
341 quiet S<"C<use strict 'vars'>">.  The actual initialization is delayed until
342 run time, so it gets executed appropriately; every time through a loop,
343 for example.
344
345 Variables declared with "C<my>" are not part of any package and are therefore
346 never fully qualified with the package name.  In particular, you're not
347 allowed to try to make a package variable (or other global) lexical:
348
349     my $pack::var;      # ERROR!  Illegal syntax
350     my $_;              # also illegal (currently)
351
352 In fact, a dynamic variable (also known as package or global variables)
353 are still accessible using the fully qualified C<::> notation even while a
354 lexical of the same name is also visible:
355
356     package main;
357     local $x = 10;
358     my    $x = 20;
359     print "$x and $::x\n";
360
361 That will print out C<20> and C<10>.
362
363 You may declare "C<my>" variables at the outermost scope of a file to hide
364 any such identifiers totally from the outside world.  This is similar
365 to C's static variables at the file level.  To do this with a subroutine
366 requires the use of a closure (anonymous function with lexical access).
367 If a block (such as an C<eval()>, function, or C<package>) wants to create
368 a private subroutine that cannot be called from outside that block,
369 it can declare a lexical variable containing an anonymous sub reference:
370
371     my $secret_version = '1.001-beta';
372     my $secret_sub = sub { print $secret_version };
373     &$secret_sub();
374
375 As long as the reference is never returned by any function within the
376 module, no outside module can see the subroutine, because its name is not in
377 any package's symbol table.  Remember that it's not I<REALLY> called
378 C<$some_pack::secret_version> or anything; it's just C<$secret_version>,
379 unqualified and unqualifiable.
380
381 This does not work with object methods, however; all object methods have
382 to be in the symbol table of some package to be found.
383
384 =head2 Persistent Private Variables
385
386 Just because a lexical variable is lexically (also called statically)
387 scoped to its enclosing block, C<eval>, or C<do> FILE, this doesn't mean that
388 within a function it works like a C static.  It normally works more
389 like a C auto, but with implicit garbage collection.  
390
391 Unlike local variables in C or C++, Perl's lexical variables don't
392 necessarily get recycled just because their scope has exited.
393 If something more permanent is still aware of the lexical, it will
394 stick around.  So long as something else references a lexical, that
395 lexical won't be freed--which is as it should be.  You wouldn't want
396 memory being free until you were done using it, or kept around once you
397 were done.  Automatic garbage collection takes care of this for you.
398
399 This means that you can pass back or save away references to lexical
400 variables, whereas to return a pointer to a C auto is a grave error.
401 It also gives us a way to simulate C's function statics.  Here's a
402 mechanism for giving a function private variables with both lexical
403 scoping and a static lifetime.  If you do want to create something like
404 C's static variables, just enclose the whole function in an extra block,
405 and put the static variable outside the function but in the block.
406
407     {
408         my $secret_val = 0;
409         sub gimme_another {
410             return ++$secret_val;
411         }
412     }
413     # $secret_val now becomes unreachable by the outside
414     # world, but retains its value between calls to gimme_another
415
416 If this function is being sourced in from a separate file
417 via C<require> or C<use>, then this is probably just fine.  If it's
418 all in the main program, you'll need to arrange for the C<my()>
419 to be executed early, either by putting the whole block above
420 your main program, or more likely, placing merely a C<BEGIN>
421 sub around it to make sure it gets executed before your program
422 starts to run:
423
424     sub BEGIN {
425         my $secret_val = 0;
426         sub gimme_another {
427             return ++$secret_val;
428         }
429     }
430
431 See L<perlmod/"Package Constructors and Destructors"> about the C<BEGIN> function.
432
433 If declared at the outermost scope, the file scope, then lexicals work
434 someone like C's file statics.  They are available to all functions in
435 that same file declared below them, but are inaccessible from outside of
436 the file.  This is sometimes used in modules to create private variables
437 for the whole module.
438
439 =head2 Temporary Values via local()
440
441 B<NOTE>: In general, you should be using "C<my>" instead of "C<local>", because
442 it's faster and safer.  Exceptions to this include the global punctuation
443 variables, filehandles and formats, and direct manipulation of the Perl
444 symbol table itself.  Format variables often use "C<local>" though, as do
445 other variables whose current value must be visible to called
446 subroutines.
447
448 Synopsis:
449
450     local $foo;                 # declare $foo dynamically local
451     local (@wid, %get);         # declare list of variables local
452     local $foo = "flurp";       # declare $foo dynamic, and init it
453     local @oof = @bar;          # declare @oof dynamic, and init it
454
455     local *FH;                  # localize $FH, @FH, %FH, &FH  ...
456     local *merlyn = *randal;    # now $merlyn is really $randal, plus
457                                 #     @merlyn is really @randal, etc
458     local *merlyn = 'randal';   # SAME THING: promote 'randal' to *randal
459     local *merlyn = \$randal;   # just alias $merlyn, not @merlyn etc
460
461 A C<local()> modifies its listed variables to be "local" to the enclosing
462 block, C<eval>, or C<do FILE>--and to I<any subroutine called from within that block>.
463 A C<local()> just gives temporary values to global (meaning package)
464 variables.  It does B<not> create a local variable.  This is known as
465 dynamic scoping.  Lexical scoping is done with "C<my>", which works more
466 like C's auto declarations.
467
468 If more than one variable is given to C<local()>, they must be placed in
469 parentheses.  All listed elements must be legal lvalues.  This operator works
470 by saving the current values of those variables in its argument list on a
471 hidden stack and restoring them upon exiting the block, subroutine, or
472 eval.  This means that called subroutines can also reference the local
473 variable, but not the global one.  The argument list may be assigned to if
474 desired, which allows you to initialize your local variables.  (If no
475 initializer is given for a particular variable, it is created with an
476 undefined value.)  Commonly this is used to name the parameters to a
477 subroutine.  Examples:
478
479     for $i ( 0 .. 9 ) {
480         $digits{$i} = $i;
481     }
482     # assume this function uses global %digits hash
483     parse_num();
484
485     # now temporarily add to %digits hash
486     if ($base12) {
487         # (NOTE: not claiming this is efficient!)
488         local %digits  = (%digits, 't' => 10, 'e' => 11);
489         parse_num();  # parse_num gets this new %digits!
490     }
491     # old %digits restored here
492
493 Because C<local()> is a run-time command, it gets executed every time
494 through a loop.  In releases of Perl previous to 5.0, this used more stack
495 storage each time until the loop was exited.  Perl now reclaims the space
496 each time through, but it's still more efficient to declare your variables
497 outside the loop.
498
499 A C<local> is simply a modifier on an lvalue expression.  When you assign to
500 a C<local>ized variable, the C<local> doesn't change whether its list is viewed
501 as a scalar or an array.  So
502
503     local($foo) = <STDIN>;
504     local @FOO = <STDIN>;
505
506 both supply a list context to the right-hand side, while
507
508     local $foo = <STDIN>;
509
510 supplies a scalar context.
511
512 A note about C<local()> and composite types is in order.  Something
513 like C<local(%foo)> works by temporarily placing a brand new hash in
514 the symbol table.  The old hash is left alone, but is hidden "behind"
515 the new one.
516
517 This means the old variable is completely invisible via the symbol
518 table (i.e. the hash entry in the C<*foo> typeglob) for the duration
519 of the dynamic scope within which the C<local()> was seen.  This
520 has the effect of allowing one to temporarily occlude any magic on
521 composite types.  For instance, this will briefly alter a tied
522 hash to some other implementation:
523
524     tie %ahash, 'APackage';
525     [...]
526     {
527        local %ahash;
528        tie %ahash, 'BPackage';
529        [..called code will see %ahash tied to 'BPackage'..]
530        {
531           local %ahash;
532           [..%ahash is a normal (untied) hash here..]
533        }
534     }
535     [..%ahash back to its initial tied self again..]
536
537 As another example, a custom implementation of C<%ENV> might look
538 like this:
539
540     {
541         local %ENV;
542         tie %ENV, 'MyOwnEnv';
543         [..do your own fancy %ENV manipulation here..]
544     }
545     [..normal %ENV behavior here..]
546
547 It's also worth taking a moment to explain what happens when you
548 C<local>ize a member of a composite type (i.e. an array or hash element).
549 In this case, the element is C<local>ized I<by name>. This means that
550 when the scope of the C<local()> ends, the saved value will be
551 restored to the hash element whose key was named in the C<local()>, or
552 the array element whose index was named in the C<local()>.  If that
553 element was deleted while the C<local()> was in effect (e.g. by a
554 C<delete()> from a hash or a C<shift()> of an array), it will spring
555 back into existence, possibly extending an array and filling in the
556 skipped elements with C<undef>.  For instance, if you say
557
558     %hash = ( 'This' => 'is', 'a' => 'test' );
559     @ary  = ( 0..5 );
560     {
561          local($ary[5]) = 6;
562          local($hash{'a'}) = 'drill';
563          while (my $e = pop(@ary)) {
564              print "$e . . .\n";
565              last unless $e > 3;
566          }
567          if (@ary) {
568              $hash{'only a'} = 'test';
569              delete $hash{'a'};
570          }
571     }
572     print join(' ', map { "$_ $hash{$_}" } sort keys %hash),".\n";
573     print "The array has ",scalar(@ary)," elements: ",
574           join(', ', map { defined $_ ? $_ : 'undef' } @ary),"\n";
575
576 Perl will print
577
578     6 . . .
579     4 . . .
580     3 . . .
581     This is a test only a test.
582     The array has 6 elements: 0, 1, 2, undef, undef, 5
583
584 Note also that when you C<local>ize a member of a composite type that
585 B<does not exist previously>, the value is treated as though it were
586 in an lvalue context, i.e., it is first created and then C<local>ized.
587 The consequence of this is that the hash or array is in fact permanently
588 modified. For instance, if you say
589
590     %hash = ( 'This' => 'is', 'a' => 'test' );
591     @ary  = ( 0..5 );
592     {
593         local($ary[8]) = 0;
594         local($hash{'b'}) = 'whatever';
595     }
596     printf "%%hash has now %d keys, \@ary %d elements.\n",
597         scalar(keys(%hash)), scalar(@ary);
598
599 Perl will print
600
601     %hash has now 3 keys, @ary 9 elements.
602
603 The above behavior of local() on non-existent members of composite
604 types is subject to change in future.
605
606 =head2 Passing Symbol Table Entries (typeglobs)
607
608 [Note:  The mechanism described in this section was originally the only
609 way to simulate pass-by-reference in older versions of Perl.  While it
610 still works fine in modern versions, the new reference mechanism is
611 generally easier to work with.  See below.]
612
613 Sometimes you don't want to pass the value of an array to a subroutine
614 but rather the name of it, so that the subroutine can modify the global
615 copy of it rather than working with a local copy.  In perl you can
616 refer to all objects of a particular name by prefixing the name
617 with a star: C<*foo>.  This is often known as a "typeglob", because the
618 star on the front can be thought of as a wildcard match for all the
619 funny prefix characters on variables and subroutines and such.
620
621 When evaluated, the typeglob produces a scalar value that represents
622 all the objects of that name, including any filehandle, format, or
623 subroutine.  When assigned to, it causes the name mentioned to refer to
624 whatever "C<*>" value was assigned to it.  Example:
625
626     sub doubleary {
627         local(*someary) = @_;
628         foreach $elem (@someary) {
629             $elem *= 2;
630         }
631     }
632     doubleary(*foo);
633     doubleary(*bar);
634
635 Note that scalars are already passed by reference, so you can modify
636 scalar arguments without using this mechanism by referring explicitly
637 to C<$_[0]> etc.  You can modify all the elements of an array by passing
638 all the elements as scalars, but you have to use the C<*> mechanism (or
639 the equivalent reference mechanism) to C<push>, C<pop>, or change the size of
640 an array.  It will certainly be faster to pass the typeglob (or reference).
641
642 Even if you don't want to modify an array, this mechanism is useful for
643 passing multiple arrays in a single LIST, because normally the LIST
644 mechanism will merge all the array values so that you can't extract out
645 the individual arrays.  For more on typeglobs, see
646 L<perldata/"Typeglobs and Filehandles">.
647
648 =head2 When to Still Use local()
649
650 Despite the existence of C<my()>, there are still three places where the
651 C<local()> operator still shines.  In fact, in these three places, you
652 I<must> use C<local> instead of C<my>.
653
654 =over
655
656 =item 1. You need to give a global variable a temporary value, especially C<$_>.
657
658 The global variables, like C<@ARGV> or the punctuation variables, must be 
659 C<local>ized with C<local()>.  This block reads in F</etc/motd>, and splits
660 it up into chunks separated by lines of equal signs, which are placed
661 in C<@Fields>.
662
663     {
664         local @ARGV = ("/etc/motd");
665         local $/ = undef;
666         local $_ = <>;  
667         @Fields = split /^\s*=+\s*$/;
668     } 
669
670 It particular, it's important to C<local>ize C<$_> in any routine that assigns
671 to it.  Look out for implicit assignments in C<while> conditionals.
672
673 =item 2. You need to create a local file or directory handle or a local function.
674
675 A function that needs a filehandle of its own must use C<local()> uses
676 C<local()> on complete typeglob.   This can be used to create new symbol
677 table entries:
678
679     sub ioqueue {
680         local  (*READER, *WRITER);    # not my!
681         pipe    (READER,  WRITER);    or die "pipe: $!";
682         return (*READER, *WRITER);
683     }
684     ($head, $tail) = ioqueue();
685
686 See the Symbol module for a way to create anonymous symbol table
687 entries.
688
689 Because assignment of a reference to a typeglob creates an alias, this
690 can be used to create what is effectively a local function, or at least,
691 a local alias.
692
693     {
694         local *grow = \&shrink; # only until this block exists
695         grow();                 # really calls shrink()
696         move();                 # if move() grow()s, it shrink()s too
697     }
698     grow();                     # get the real grow() again
699
700 See L<perlref/"Function Templates"> for more about manipulating
701 functions by name in this way.
702
703 =item 3. You want to temporarily change just one element of an array or hash.
704
705 You can C<local>ize just one element of an aggregate.  Usually this
706 is done on dynamics:
707
708     {
709         local $SIG{INT} = 'IGNORE';
710         funct();                            # uninterruptible
711     } 
712     # interruptibility automatically restored here
713
714 But it also works on lexically declared aggregates.  Prior to 5.005,
715 this operation could on occasion misbehave.
716
717 =back
718
719 =head2 Pass by Reference
720
721 If you want to pass more than one array or hash into a function--or
722 return them from it--and have them maintain their integrity, then
723 you're going to have to use an explicit pass-by-reference.  Before you
724 do that, you need to understand references as detailed in L<perlref>.
725 This section may not make much sense to you otherwise.
726
727 Here are a few simple examples.  First, let's pass in several
728 arrays to a function and have it C<pop> all of then, return a new
729 list of all their former last elements:
730
731     @tailings = popmany ( \@a, \@b, \@c, \@d );
732
733     sub popmany {
734         my $aref;
735         my @retlist = ();
736         foreach $aref ( @_ ) {
737             push @retlist, pop @$aref;
738         }
739         return @retlist;
740     }
741
742 Here's how you might write a function that returns a
743 list of keys occurring in all the hashes passed to it:
744
745     @common = inter( \%foo, \%bar, \%joe );
746     sub inter {
747         my ($k, $href, %seen); # locals
748         foreach $href (@_) {
749             while ( $k = each %$href ) {
750                 $seen{$k}++;
751             }
752         }
753         return grep { $seen{$_} == @_ } keys %seen;
754     }
755
756 So far, we're using just the normal list return mechanism.
757 What happens if you want to pass or return a hash?  Well,
758 if you're using only one of them, or you don't mind them
759 concatenating, then the normal calling convention is ok, although
760 a little expensive.
761
762 Where people get into trouble is here:
763
764     (@a, @b) = func(@c, @d);
765 or
766     (%a, %b) = func(%c, %d);
767
768 That syntax simply won't work.  It sets just C<@a> or C<%a> and clears the C<@b> or
769 C<%b>.  Plus the function didn't get passed into two separate arrays or
770 hashes: it got one long list in C<@_>, as always.
771
772 If you can arrange for everyone to deal with this through references, it's
773 cleaner code, although not so nice to look at.  Here's a function that
774 takes two array references as arguments, returning the two array elements
775 in order of how many elements they have in them:
776
777     ($aref, $bref) = func(\@c, \@d);
778     print "@$aref has more than @$bref\n";
779     sub func {
780         my ($cref, $dref) = @_;
781         if (@$cref > @$dref) {
782             return ($cref, $dref);
783         } else {
784             return ($dref, $cref);
785         }
786     }
787
788 It turns out that you can actually do this also:
789
790     (*a, *b) = func(\@c, \@d);
791     print "@a has more than @b\n";
792     sub func {
793         local (*c, *d) = @_;
794         if (@c > @d) {
795             return (\@c, \@d);
796         } else {
797             return (\@d, \@c);
798         }
799     }
800
801 Here we're using the typeglobs to do symbol table aliasing.  It's
802 a tad subtle, though, and also won't work if you're using C<my()>
803 variables, because only globals (well, and C<local()>s) are in the symbol table.
804
805 If you're passing around filehandles, you could usually just use the bare
806 typeglob, like C<*STDOUT>, but typeglobs references would be better because
807 they'll still work properly under S<C<use strict 'refs'>>.  For example:
808
809     splutter(\*STDOUT);
810     sub splutter {
811         my $fh = shift;
812         print $fh "her um well a hmmm\n";
813     }
814
815     $rec = get_rec(\*STDIN);
816     sub get_rec {
817         my $fh = shift;
818         return scalar <$fh>;
819     }
820
821 Another way to do this is using C<*HANDLE{IO}>, see L<perlref> for usage
822 and caveats.
823
824 If you're planning on generating new filehandles, you could do this:
825
826     sub openit {
827         my $name = shift;
828         local *FH;
829         return open (FH, $path) ? *FH : undef;
830     }
831
832 Although that will actually produce a small memory leak.  See the bottom
833 of L<perlfunc/open()> for a somewhat cleaner way using the C<IO::Handle>
834 package.
835
836 =head2 Prototypes
837
838 As of the 5.002 release of perl, if you declare
839
840     sub mypush (\@@)
841
842 then C<mypush()> takes arguments exactly like C<push()> does.  The declaration
843 of the function to be called must be visible at compile time.  The prototype
844 affects only the interpretation of new-style calls to the function, where
845 new-style is defined as not using the C<&> character.  In other words,
846 if you call it like a builtin function, then it behaves like a builtin
847 function.  If you call it like an old-fashioned subroutine, then it
848 behaves like an old-fashioned subroutine.  It naturally falls out from
849 this rule that prototypes have no influence on subroutine references
850 like C<\&foo> or on indirect subroutine calls like C<&{$subref}> or
851 C<$subref-E<gt>()>. 
852
853 Method calls are not influenced by prototypes either, because the
854 function to be called is indeterminate at compile time, because it depends
855 on inheritance.
856
857 Because the intent is primarily to let you define subroutines that work
858 like builtin commands, here are the prototypes for some other functions
859 that parse almost exactly like the corresponding builtins.
860
861     Declared as                 Called as
862
863     sub mylink ($$)          mylink $old, $new
864     sub myvec ($$$)          myvec $var, $offset, 1
865     sub myindex ($$;$)       myindex &getstring, "substr"
866     sub mysyswrite ($$$;$)   mysyswrite $buf, 0, length($buf) - $off, $off
867     sub myreverse (@)        myreverse $a, $b, $c
868     sub myjoin ($@)          myjoin ":", $a, $b, $c
869     sub mypop (\@)           mypop @array
870     sub mysplice (\@$$@)     mysplice @array, @array, 0, @pushme
871     sub mykeys (\%)          mykeys %{$hashref}
872     sub myopen (*;$)         myopen HANDLE, $name
873     sub mypipe (**)          mypipe READHANDLE, WRITEHANDLE
874     sub mygrep (&@)          mygrep { /foo/ } $a, $b, $c
875     sub myrand ($)           myrand 42
876     sub mytime ()            mytime
877
878 Any backslashed prototype character represents an actual argument
879 that absolutely must start with that character.  The value passed
880 to the subroutine (as part of C<@_>) will be a reference to the
881 actual argument given in the subroutine call, obtained by applying
882 C<\> to that argument.
883
884 Unbackslashed prototype characters have special meanings.  Any
885 unbackslashed C<@> or C<%> eats all the rest of the arguments, and forces
886 list context.  An argument represented by C<$> forces scalar context.  An
887 C<&> requires an anonymous subroutine, which, if passed as the first
888 argument, does not require the "C<sub>" keyword or a subsequent comma.  A
889 C<*> allows the subroutine to accept a bareword, constant, scalar expression,
890 typeglob, or a reference to a typeglob in that slot.  The value will be
891 available to the subroutine either as a simple scalar, or (in the latter
892 two cases) as a reference to the typeglob.
893
894 A semicolon separates mandatory arguments from optional arguments.
895 (It is redundant before C<@> or C<%>.)
896
897 Note how the last three examples above are treated specially by the parser.
898 C<mygrep()> is parsed as a true list operator, C<myrand()> is parsed as a
899 true unary operator with unary precedence the same as C<rand()>, and
900 C<mytime()> is truly without arguments, just like C<time()>.  That is, if you
901 say
902
903     mytime +2;
904
905 you'll get C<mytime() + 2>, not C<mytime(2)>, which is how it would be parsed
906 without the prototype.
907
908 The interesting thing about C<&> is that you can generate new syntax with it:
909
910     sub try (&@) {
911         my($try,$catch) = @_;
912         eval { &$try };
913         if ($@) {
914             local $_ = $@;
915             &$catch;
916         }
917     }
918     sub catch (&) { $_[0] }
919
920     try {
921         die "phooey";
922     } catch {
923         /phooey/ and print "unphooey\n";
924     };
925
926 That prints C<"unphooey">.  (Yes, there are still unresolved
927 issues having to do with the visibility of C<@_>.  I'm ignoring that
928 question for the moment.  (But note that if we make C<@_> lexically
929 scoped, those anonymous subroutines can act like closures... (Gee,
930 is this sounding a little Lispish?  (Never mind.))))
931
932 And here's a reimplementation of C<grep>:
933
934     sub mygrep (&@) {
935         my $code = shift;
936         my @result;
937         foreach $_ (@_) {
938             push(@result, $_) if &$code;
939         }
940         @result;
941     }
942
943 Some folks would prefer full alphanumeric prototypes.  Alphanumerics have
944 been intentionally left out of prototypes for the express purpose of
945 someday in the future adding named, formal parameters.  The current
946 mechanism's main goal is to let module writers provide better diagnostics
947 for module users.  Larry feels the notation quite understandable to Perl
948 programmers, and that it will not intrude greatly upon the meat of the
949 module, nor make it harder to read.  The line noise is visually
950 encapsulated into a small pill that's easy to swallow.
951
952 It's probably best to prototype new functions, not retrofit prototyping
953 into older ones.  That's because you must be especially careful about
954 silent impositions of differing list versus scalar contexts.  For example,
955 if you decide that a function should take just one parameter, like this:
956
957     sub func ($) {
958         my $n = shift;
959         print "you gave me $n\n";
960     }
961
962 and someone has been calling it with an array or expression
963 returning a list:
964
965     func(@foo);
966     func( split /:/ );
967
968 Then you've just supplied an automatic C<scalar()> in front of their
969 argument, which can be more than a bit surprising.  The old C<@foo>
970 which used to hold one thing doesn't get passed in.  Instead,
971 the C<func()> now gets passed in C<1>, that is, the number of elements
972 in C<@foo>.  And the C<split()> gets called in a scalar context and
973 starts scribbling on your C<@_> parameter list.
974
975 This is all very powerful, of course, and should be used only in moderation
976 to make the world a better place.
977
978 =head2 Constant Functions
979
980 Functions with a prototype of C<()> are potential candidates for
981 inlining.  If the result after optimization and constant folding is
982 either a constant or a lexically-scoped scalar which has no other
983 references, then it will be used in place of function calls made
984 without C<&> or C<do>. Calls made using C<&> or C<do> are never
985 inlined.  (See F<constant.pm> for an easy way to declare most
986 constants.)
987
988 The following functions would all be inlined:
989
990     sub pi ()           { 3.14159 }             # Not exact, but close.
991     sub PI ()           { 4 * atan2 1, 1 }      # As good as it gets,
992                                                 # and it's inlined, too!
993     sub ST_DEV ()       { 0 }
994     sub ST_INO ()       { 1 }
995
996     sub FLAG_FOO ()     { 1 << 8 }
997     sub FLAG_BAR ()     { 1 << 9 }
998     sub FLAG_MASK ()    { FLAG_FOO | FLAG_BAR }
999
1000     sub OPT_BAZ ()      { not (0x1B58 & FLAG_MASK) }
1001     sub BAZ_VAL () {
1002         if (OPT_BAZ) {
1003             return 23;
1004         }
1005         else {
1006             return 42;
1007         }
1008     }
1009
1010     sub N () { int(BAZ_VAL) / 3 }
1011     BEGIN {
1012         my $prod = 1;
1013         for (1..N) { $prod *= $_ }
1014         sub N_FACTORIAL () { $prod }
1015     }
1016
1017 If you redefine a subroutine that was eligible for inlining, you'll get
1018 a mandatory warning.  (You can use this warning to tell whether or not a
1019 particular subroutine is considered constant.)  The warning is
1020 considered severe enough not to be optional because previously compiled
1021 invocations of the function will still be using the old value of the
1022 function.  If you need to be able to redefine the subroutine you need to
1023 ensure that it isn't inlined, either by dropping the C<()> prototype
1024 (which changes the calling semantics, so beware) or by thwarting the
1025 inlining mechanism in some other way, such as
1026
1027     sub not_inlined () {
1028         23 if $];
1029     }
1030
1031 =head2 Overriding Builtin Functions
1032
1033 Many builtin functions may be overridden, though this should be tried
1034 only occasionally and for good reason.  Typically this might be
1035 done by a package attempting to emulate missing builtin functionality
1036 on a non-Unix system.
1037
1038 Overriding may be done only by importing the name from a
1039 module--ordinary predeclaration isn't good enough.  However, the
1040 C<subs> pragma (compiler directive) lets you, in effect, predeclare subs
1041 via the import syntax, and these names may then override the builtin ones:
1042
1043     use subs 'chdir', 'chroot', 'chmod', 'chown';
1044     chdir $somewhere;
1045     sub chdir { ... }
1046
1047 To unambiguously refer to the builtin form, one may precede the
1048 builtin name with the special package qualifier C<CORE::>.  For example,
1049 saying C<CORE::open()> will always refer to the builtin C<open()>, even
1050 if the current package has imported some other subroutine called
1051 C<&open()> from elsewhere.
1052
1053 Library modules should not in general export builtin names like "C<open>"
1054 or "C<chdir>" as part of their default C<@EXPORT> list, because these may
1055 sneak into someone else's namespace and change the semantics unexpectedly.
1056 Instead, if the module adds the name to the C<@EXPORT_OK> list, then it's
1057 possible for a user to import the name explicitly, but not implicitly.
1058 That is, they could say
1059
1060     use Module 'open';
1061
1062 and it would import the C<open> override, but if they said
1063
1064     use Module;
1065
1066 they would get the default imports without the overrides.
1067
1068 The foregoing mechanism for overriding builtins is restricted, quite
1069 deliberately, to the package that requests the import.  There is a second
1070 method that is sometimes applicable when you wish to override a builtin
1071 everywhere, without regard to namespace boundaries.  This is achieved by
1072 importing a sub into the special namespace C<CORE::GLOBAL::>.  Here is an
1073 example that quite brazenly replaces the C<glob> operator with something
1074 that understands regular expressions.
1075
1076     package REGlob;
1077     require Exporter;
1078     @ISA = 'Exporter';
1079     @EXPORT_OK = 'glob';
1080
1081     sub import {
1082         my $pkg = shift;
1083         return unless @_;
1084         my $sym = shift;
1085         my $where = ($sym =~ s/^GLOBAL_// ? 'CORE::GLOBAL' : caller(0));
1086         $pkg->export($where, $sym, @_);
1087     }
1088
1089     sub glob {
1090         my $pat = shift;
1091         my @got;
1092         local(*D);
1093         if (opendir D, '.') { @got = grep /$pat/, readdir D; closedir D; }
1094         @got;
1095     }
1096     1;
1097
1098 And here's how it could be (ab)used:
1099
1100     #use REGlob 'GLOBAL_glob';      # override glob() in ALL namespaces
1101     package Foo;
1102     use REGlob 'glob';              # override glob() in Foo:: only
1103     print for <^[a-z_]+\.pm\$>;     # show all pragmatic modules
1104
1105 Note that the initial comment shows a contrived, even dangerous example.
1106 By overriding C<glob> globally, you would be forcing the new (and
1107 subversive) behavior for the C<glob> operator for B<every> namespace,
1108 without the complete cognizance or cooperation of the modules that own
1109 those namespaces.  Naturally, this should be done with extreme caution--if
1110 it must be done at all.
1111
1112 The C<REGlob> example above does not implement all the support needed to
1113 cleanly override perl's C<glob> operator.  The builtin C<glob> has
1114 different behaviors depending on whether it appears in a scalar or list
1115 context, but our C<REGlob> doesn't.  Indeed, many perl builtins have such
1116 context sensitive behaviors, and these must be adequately supported by
1117 a properly written override.  For a fully functional example of overriding
1118 C<glob>, study the implementation of C<File::DosGlob> in the standard
1119 library.
1120
1121
1122 =head2 Autoloading
1123
1124 If you call a subroutine that is undefined, you would ordinarily get an
1125 immediate fatal error complaining that the subroutine doesn't exist.
1126 (Likewise for subroutines being used as methods, when the method
1127 doesn't exist in any base class of the class package.) If,
1128 however, there is an C<AUTOLOAD> subroutine defined in the package or
1129 packages that were searched for the original subroutine, then that
1130 C<AUTOLOAD> subroutine is called with the arguments that would have been
1131 passed to the original subroutine.  The fully qualified name of the
1132 original subroutine magically appears in the C<$AUTOLOAD> variable in the
1133 same package as the C<AUTOLOAD> routine.  The name is not passed as an
1134 ordinary argument because, er, well, just because, that's why...
1135
1136 Most C<AUTOLOAD> routines will load in a definition for the subroutine in
1137 question using eval, and then execute that subroutine using a special
1138 form of "goto" that erases the stack frame of the C<AUTOLOAD> routine
1139 without a trace.  (See the standard C<AutoLoader> module, for example.)
1140 But an C<AUTOLOAD> routine can also just emulate the routine and never
1141 define it.   For example, let's pretend that a function that wasn't defined
1142 should just call C<system()> with those arguments.  All you'd do is this:
1143
1144     sub AUTOLOAD {
1145         my $program = $AUTOLOAD;
1146         $program =~ s/.*:://;
1147         system($program, @_);
1148     }
1149     date();
1150     who('am', 'i');
1151     ls('-l');
1152
1153 In fact, if you predeclare the functions you want to call that way, you don't
1154 even need the parentheses:
1155
1156     use subs qw(date who ls);
1157     date;
1158     who "am", "i";
1159     ls -l;
1160
1161 A more complete example of this is the standard Shell module, which
1162 can treat undefined subroutine calls as calls to Unix programs.
1163
1164 Mechanisms are available for modules writers to help split the modules
1165 up into autoloadable files.  See the standard AutoLoader module
1166 described in L<AutoLoader> and in L<AutoSplit>, the standard
1167 SelfLoader modules in L<SelfLoader>, and the document on adding C
1168 functions to perl code in L<perlxs>.
1169
1170 =head1 SEE ALSO
1171
1172 See L<perlref> for more about references and closures.  See L<perlxs> if
1173 you'd like to learn about calling C subroutines from perl.  See L<perlmod>
1174 to learn about bundling up your functions in separate files.