Clean up and document API for hashes
[p5sagit/p5-mst-13.2.git] / pod / perlsub.pod
CommitLineData
a0d0e21e 1=head1 NAME
2
3perlsub - Perl subroutines
4
5=head1 SYNOPSIS
6
7To declare subroutines:
8
cb1a09d0 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
a0d0e21e 14
748a9306 15To define an anonymous subroutine at runtime:
16
17 $subref = sub BLOCK;
18
a0d0e21e 19To import subroutines:
20
21 use PACKAGE qw(NAME1 NAME2 NAME3);
22
23To call subroutines:
24
5f05dabc 25 NAME(LIST); # & is optional with parentheses.
26 NAME LIST; # Parentheses optional if pre-declared/imported.
cb1a09d0 27 &NAME; # Passes current @_ to subroutine.
a0d0e21e 28
29=head1 DESCRIPTION
30
cb1a09d0 31Like many languages, Perl provides for user-defined subroutines. These
32may be located anywhere in the main program, loaded in from other files
33via the C<do>, C<require>, or C<use> keywords, or even generated on the
34fly using C<eval> or anonymous subroutines (closures). You can even call
c07a80fd 35a function indirectly using a variable containing its name or a CODE reference
36to it, as in C<$var = \&function>.
cb1a09d0 37
38The Perl model for function call and return values is simple: all
39functions are passed as parameters one single flat list of scalars, and
40all functions likewise return to their caller one single flat list of
41scalars. Any arrays or hashes in these call and return lists will
42collapse, losing their identities--but you may always use
43pass-by-reference instead to avoid this. Both call and return lists may
44contain as many or as few scalar elements as you'd like. (Often a
45function without an explicit return statement is called a subroutine, but
46there's really no difference from the language's perspective.)
47
48Any arguments passed to the routine come in as the array @_. Thus if you
49called a function with two arguments, those would be stored in C<$_[0]>
50and C<$_[1]>. The array @_ is a local array, but its values are implicit
dfdcb7a0 51references (predating L<perlref>) to the actual scalar parameters. What
52this means in practice is that when you explicitly modify C<$_[0]> et al.,
53you will be changing the actual arguments. As a result, all arguments
54to functions are treated as lvalues. Any hash or array elements that are
55passed to functions will get created if they do not exist (irrespective
56of whether the function does modify the contents of C<@_>). This is
57frequently a source of surprise. See L<perltrap> for an example.
58
59The return value of the subroutine is the value of the last expression
cb1a09d0 60evaluated. Alternatively, a return statement may be used to specify the
61returned value and exit the subroutine. If you return one or more arrays
62and/or hashes, these will be flattened together into one large
63indistinguishable list.
64
65Perl does not have named formal parameters, but in practice all you do is
66assign to a my() list of these. Any variables you use in the function
67that aren't declared private are global variables. For the gory details
1fef88e7 68on creating private variables, see
6d28dffb 69L<"Private Variables via my()"> and L<"Temporary Values via local()">.
70To create protected environments for a set of functions in a separate
71package (and probably a separate file), see L<perlmod/"Packages">.
a0d0e21e 72
73Example:
74
cb1a09d0 75 sub max {
76 my $max = shift(@_);
a0d0e21e 77 foreach $foo (@_) {
78 $max = $foo if $max < $foo;
79 }
cb1a09d0 80 return $max;
a0d0e21e 81 }
cb1a09d0 82 $bestday = max($mon,$tue,$wed,$thu,$fri);
a0d0e21e 83
84Example:
85
86 # get a line, combining continuation lines
87 # that start with whitespace
88
89 sub get_line {
cb1a09d0 90 $thisline = $lookahead; # GLOBAL VARIABLES!!
a0d0e21e 91 LINE: while ($lookahead = <STDIN>) {
92 if ($lookahead =~ /^[ \t]/) {
93 $thisline .= $lookahead;
94 }
95 else {
96 last LINE;
97 }
98 }
99 $thisline;
100 }
101
102 $lookahead = <STDIN>; # get first line
103 while ($_ = get_line()) {
104 ...
105 }
106
107Use array assignment to a local list to name your formal arguments:
108
109 sub maybeset {
110 my($key, $value) = @_;
cb1a09d0 111 $Foo{$key} = $value unless $Foo{$key};
a0d0e21e 112 }
113
cb1a09d0 114This also has the effect of turning call-by-reference into call-by-value,
5f05dabc 115because the assignment copies the values. Otherwise a function is free to
1fef88e7 116do in-place modifications of @_ and change its caller's values.
cb1a09d0 117
118 upcase_in($v1, $v2); # this changes $v1 and $v2
119 sub upcase_in {
120 for (@_) { tr/a-z/A-Z/ }
121 }
122
123You aren't allowed to modify constants in this way, of course. If an
124argument were actually literal and you tried to change it, you'd take a
125(presumably fatal) exception. For example, this won't work:
126
127 upcase_in("frederick");
128
129It would be much safer if the upcase_in() function
130were written to return a copy of its parameters instead
131of changing them in place:
132
133 ($v3, $v4) = upcase($v1, $v2); # this doesn't
134 sub upcase {
135 my @parms = @_;
136 for (@parms) { tr/a-z/A-Z/ }
c07a80fd 137 # wantarray checks if we were called in list context
138 return wantarray ? @parms : $parms[0];
cb1a09d0 139 }
140
141Notice how this (unprototyped) function doesn't care whether it was passed
142real scalars or arrays. Perl will see everything as one big long flat @_
143parameter list. This is one of the ways where Perl's simple
144argument-passing style shines. The upcase() function would work perfectly
145well without changing the upcase() definition even if we fed it things
146like this:
147
148 @newlist = upcase(@list1, @list2);
149 @newlist = upcase( split /:/, $var );
150
151Do not, however, be tempted to do this:
152
153 (@a, @b) = upcase(@list1, @list2);
154
155Because like its flat incoming parameter list, the return list is also
156flat. So all you have managed to do here is stored everything in @a and
157made @b an empty list. See L</"Pass by Reference"> for alternatives.
158
5f05dabc 159A subroutine may be called using the "&" prefix. The "&" is optional
160in modern Perls, and so are the parentheses if the subroutine has been
161pre-declared. (Note, however, that the "&" is I<NOT> optional when
162you're just naming the subroutine, such as when it's used as an
163argument to defined() or undef(). Nor is it optional when you want to
164do an indirect subroutine call with a subroutine name or reference
165using the C<&$subref()> or C<&{$subref}()> constructs. See L<perlref>
166for more on that.)
a0d0e21e 167
168Subroutines may be called recursively. If a subroutine is called using
cb1a09d0 169the "&" form, the argument list is optional, and if omitted, no @_ array is
170set up for the subroutine: the @_ array at the time of the call is
171visible to subroutine instead. This is an efficiency mechanism that
172new users may wish to avoid.
a0d0e21e 173
174 &foo(1,2,3); # pass three arguments
175 foo(1,2,3); # the same
176
177 foo(); # pass a null list
178 &foo(); # the same
a0d0e21e 179
cb1a09d0 180 &foo; # foo() get current args, like foo(@_) !!
181 foo; # like foo() IFF sub foo pre-declared, else "foo"
182
c07a80fd 183Not only does the "&" form make the argument list optional, but it also
184disables any prototype checking on the arguments you do provide. This
185is partly for historical reasons, and partly for having a convenient way
186to cheat if you know what you're doing. See the section on Prototypes below.
187
cb1a09d0 188=head2 Private Variables via my()
189
190Synopsis:
191
192 my $foo; # declare $foo lexically local
193 my (@wid, %get); # declare list of variables local
194 my $foo = "flurp"; # declare $foo lexical, and init it
195 my @oof = @bar; # declare @oof lexical, and init it
196
197A "my" declares the listed variables to be confined (lexically) to the
55497cff 198enclosing block, conditional (C<if/unless/elsif/else>), loop
199(C<for/foreach/while/until/continue>), subroutine, C<eval>, or
200C<do/require/use>'d file. If more than one value is listed, the list
5f05dabc 201must be placed in parentheses. All listed elements must be legal lvalues.
55497cff 202Only alphanumeric identifiers may be lexically scoped--magical
203builtins like $/ must currently be localized with "local" instead.
cb1a09d0 204
205Unlike dynamic variables created by the "local" statement, lexical
206variables declared with "my" are totally hidden from the outside world,
207including any called subroutines (even if it's the same subroutine called
208from itself or elsewhere--every call gets its own copy).
209
210(An eval(), however, can see the lexical variables of the scope it is
211being evaluated in so long as the names aren't hidden by declarations within
212the eval() itself. See L<perlref>.)
213
214The parameter list to my() may be assigned to if desired, which allows you
215to initialize your variables. (If no initializer is given for a
216particular variable, it is created with the undefined value.) Commonly
217this is used to name the parameters to a subroutine. Examples:
218
219 $arg = "fred"; # "global" variable
220 $n = cube_root(27);
221 print "$arg thinks the root is $n\n";
222 fred thinks the root is 3
223
224 sub cube_root {
225 my $arg = shift; # name doesn't matter
226 $arg **= 1/3;
227 return $arg;
228 }
229
230The "my" is simply a modifier on something you might assign to. So when
231you do assign to the variables in its argument list, the "my" doesn't
232change whether those variables is viewed as a scalar or an array. So
233
234 my ($foo) = <STDIN>;
235 my @FOO = <STDIN>;
236
5f05dabc 237both supply a list context to the right-hand side, while
cb1a09d0 238
239 my $foo = <STDIN>;
240
5f05dabc 241supplies a scalar context. But the following declares only one variable:
748a9306 242
cb1a09d0 243 my $foo, $bar = 1;
748a9306 244
cb1a09d0 245That has the same effect as
748a9306 246
cb1a09d0 247 my $foo;
248 $bar = 1;
a0d0e21e 249
cb1a09d0 250The declared variable is not introduced (is not visible) until after
251the current statement. Thus,
252
253 my $x = $x;
254
255can be used to initialize the new $x with the value of the old $x, and
256the expression
257
258 my $x = 123 and $x == 123
259
260is false unless the old $x happened to have the value 123.
261
55497cff 262Lexical scopes of control structures are not bounded precisely by the
263braces that delimit their controlled blocks; control expressions are
264part of the scope, too. Thus in the loop
265
266 while (my $line = <>) {
267 $line = lc $line;
268 } continue {
269 print $line;
270 }
271
272the scope of $line extends from its declaration throughout the rest of
273the loop construct (including the C<continue> clause), but not beyond
274it. Similarly, in the conditional
275
276 if ((my $answer = <STDIN>) =~ /^yes$/i) {
277 user_agrees();
278 } elsif ($answer =~ /^no$/i) {
279 user_disagrees();
280 } else {
281 chomp $answer;
282 die "'$answer' is neither 'yes' nor 'no'";
283 }
284
285the scope of $answer extends from its declaration throughout the rest
286of the conditional (including C<elsif> and C<else> clauses, if any),
287but not beyond it.
288
289(None of the foregoing applies to C<if/unless> or C<while/until>
290modifiers appended to simple statements. Such modifiers are not
291control structures and have no effect on scoping.)
292
5f05dabc 293The C<foreach> loop defaults to scoping its index variable dynamically
55497cff 294(in the manner of C<local>; see below). However, if the index
295variable is prefixed with the keyword "my", then it is lexically
296scoped instead. Thus in the loop
297
298 for my $i (1, 2, 3) {
299 some_function();
300 }
301
302the scope of $i extends to the end of the loop, but not beyond it, and
303so the value of $i is unavailable in some_function().
304
cb1a09d0 305Some users may wish to encourage the use of lexically scoped variables.
306As an aid to catching implicit references to package variables,
307if you say
308
309 use strict 'vars';
310
311then any variable reference from there to the end of the enclosing
312block must either refer to a lexical variable, or must be fully
313qualified with the package name. A compilation error results
314otherwise. An inner block may countermand this with S<"no strict 'vars'">.
315
316A my() has both a compile-time and a run-time effect. At compile time,
317the compiler takes notice of it; the principle usefulness of this is to
318quiet C<use strict 'vars'>. The actual initialization doesn't happen
319until run time, so gets executed every time through a loop.
320
321Variables declared with "my" are not part of any package and are therefore
322never fully qualified with the package name. In particular, you're not
323allowed to try to make a package variable (or other global) lexical:
324
325 my $pack::var; # ERROR! Illegal syntax
326 my $_; # also illegal (currently)
327
328In fact, a dynamic variable (also known as package or global variables)
329are still accessible using the fully qualified :: notation even while a
330lexical of the same name is also visible:
331
332 package main;
333 local $x = 10;
334 my $x = 20;
335 print "$x and $::x\n";
336
337That will print out 20 and 10.
338
5f05dabc 339You may declare "my" variables at the outermost scope of a file to
340hide any such identifiers totally from the outside world. This is similar
6d28dffb 341to C's static variables at the file level. To do this with a subroutine
cb1a09d0 342requires the use of a closure (anonymous function). If a block (such as
343an eval(), function, or C<package>) wants to create a private subroutine
344that cannot be called from outside that block, it can declare a lexical
345variable containing an anonymous sub reference:
346
347 my $secret_version = '1.001-beta';
348 my $secret_sub = sub { print $secret_version };
349 &$secret_sub();
350
351As long as the reference is never returned by any function within the
5f05dabc 352module, no outside module can see the subroutine, because its name is not in
cb1a09d0 353any package's symbol table. Remember that it's not I<REALLY> called
354$some_pack::secret_version or anything; it's just $secret_version,
355unqualified and unqualifiable.
356
357This does not work with object methods, however; all object methods have
358to be in the symbol table of some package to be found.
359
360Just because the lexical variable is lexically (also called statically)
361scoped doesn't mean that within a function it works like a C static. It
362normally works more like a C auto. But here's a mechanism for giving a
363function private variables with both lexical scoping and a static
364lifetime. If you do want to create something like C's static variables,
365just enclose the whole function in an extra block, and put the
366static variable outside the function but in the block.
367
368 {
369 my $secret_val = 0;
370 sub gimme_another {
371 return ++$secret_val;
372 }
373 }
374 # $secret_val now becomes unreachable by the outside
375 # world, but retains its value between calls to gimme_another
376
377If this function is being sourced in from a separate file
378via C<require> or C<use>, then this is probably just fine. If it's
379all in the main program, you'll need to arrange for the my()
380to be executed early, either by putting the whole block above
5f05dabc 381your pain program, or more likely, placing merely a BEGIN
cb1a09d0 382sub around it to make sure it gets executed before your program
383starts to run:
384
385 sub BEGIN {
386 my $secret_val = 0;
387 sub gimme_another {
388 return ++$secret_val;
389 }
390 }
391
392See L<perlrun> about the BEGIN function.
393
394=head2 Temporary Values via local()
395
396B<NOTE>: In general, you should be using "my" instead of "local", because
6d28dffb 397it's faster and safer. Exceptions to this include the global punctuation
cb1a09d0 398variables, filehandles and formats, and direct manipulation of the Perl
399symbol table itself. Format variables often use "local" though, as do
400other variables whose current value must be visible to called
401subroutines.
402
403Synopsis:
404
405 local $foo; # declare $foo dynamically local
406 local (@wid, %get); # declare list of variables local
407 local $foo = "flurp"; # declare $foo dynamic, and init it
408 local @oof = @bar; # declare @oof dynamic, and init it
409
410 local *FH; # localize $FH, @FH, %FH, &FH ...
411 local *merlyn = *randal; # now $merlyn is really $randal, plus
412 # @merlyn is really @randal, etc
413 local *merlyn = 'randal'; # SAME THING: promote 'randal' to *randal
414 local *merlyn = \$randal; # just alias $merlyn, not @merlyn etc
415
416A local() modifies its listed variables to be local to the enclosing
5f05dabc 417block, (or subroutine, C<eval{}>, or C<do>) and I<any called from
cb1a09d0 418within that block>. A local() just gives temporary values to global
419(meaning package) variables. This is known as dynamic scoping. Lexical
420scoping is done with "my", which works more like C's auto declarations.
421
422If more than one variable is given to local(), they must be placed in
5f05dabc 423parentheses. All listed elements must be legal lvalues. This operator works
cb1a09d0 424by saving the current values of those variables in its argument list on a
5f05dabc 425hidden stack and restoring them upon exiting the block, subroutine, or
cb1a09d0 426eval. This means that called subroutines can also reference the local
427variable, but not the global one. The argument list may be assigned to if
428desired, which allows you to initialize your local variables. (If no
429initializer is given for a particular variable, it is created with an
430undefined value.) Commonly this is used to name the parameters to a
431subroutine. Examples:
432
433 for $i ( 0 .. 9 ) {
434 $digits{$i} = $i;
435 }
436 # assume this function uses global %digits hash
437 parse_num();
438
439 # now temporarily add to %digits hash
440 if ($base12) {
441 # (NOTE: not claiming this is efficient!)
442 local %digits = (%digits, 't' => 10, 'e' => 11);
443 parse_num(); # parse_num gets this new %digits!
444 }
445 # old %digits restored here
446
1fef88e7 447Because local() is a run-time command, it gets executed every time
cb1a09d0 448through a loop. In releases of Perl previous to 5.0, this used more stack
449storage each time until the loop was exited. Perl now reclaims the space
450each time through, but it's still more efficient to declare your variables
451outside the loop.
452
453A local is simply a modifier on an lvalue expression. When you assign to
454a localized variable, the local doesn't change whether its list is viewed
455as a scalar or an array. So
456
457 local($foo) = <STDIN>;
458 local @FOO = <STDIN>;
459
5f05dabc 460both supply a list context to the right-hand side, while
cb1a09d0 461
462 local $foo = <STDIN>;
463
464supplies a scalar context.
465
466=head2 Passing Symbol Table Entries (typeglobs)
467
468[Note: The mechanism described in this section was originally the only
469way to simulate pass-by-reference in older versions of Perl. While it
470still works fine in modern versions, the new reference mechanism is
471generally easier to work with. See below.]
a0d0e21e 472
473Sometimes you don't want to pass the value of an array to a subroutine
474but rather the name of it, so that the subroutine can modify the global
475copy of it rather than working with a local copy. In perl you can
cb1a09d0 476refer to all objects of a particular name by prefixing the name
5f05dabc 477with a star: C<*foo>. This is often known as a "typeglob", because the
a0d0e21e 478star on the front can be thought of as a wildcard match for all the
479funny prefix characters on variables and subroutines and such.
480
55497cff 481When evaluated, the typeglob produces a scalar value that represents
5f05dabc 482all the objects of that name, including any filehandle, format, or
a0d0e21e 483subroutine. When assigned to, it causes the name mentioned to refer to
484whatever "*" value was assigned to it. Example:
485
486 sub doubleary {
487 local(*someary) = @_;
488 foreach $elem (@someary) {
489 $elem *= 2;
490 }
491 }
492 doubleary(*foo);
493 doubleary(*bar);
494
495Note that scalars are already passed by reference, so you can modify
496scalar arguments without using this mechanism by referring explicitly
1fef88e7 497to C<$_[0]> etc. You can modify all the elements of an array by passing
a0d0e21e 498all the elements as scalars, but you have to use the * mechanism (or
5f05dabc 499the equivalent reference mechanism) to push, pop, or change the size of
a0d0e21e 500an array. It will certainly be faster to pass the typeglob (or reference).
501
502Even if you don't want to modify an array, this mechanism is useful for
5f05dabc 503passing multiple arrays in a single LIST, because normally the LIST
a0d0e21e 504mechanism will merge all the array values so that you can't extract out
55497cff 505the individual arrays. For more on typeglobs, see
506L<perldata/"Typeglobs and FileHandles">.
cb1a09d0 507
508=head2 Pass by Reference
509
55497cff 510If you want to pass more than one array or hash into a function--or
511return them from it--and have them maintain their integrity, then
512you're going to have to use an explicit pass-by-reference. Before you
513do that, you need to understand references as detailed in L<perlref>.
c07a80fd 514This section may not make much sense to you otherwise.
cb1a09d0 515
516Here are a few simple examples. First, let's pass in several
517arrays to a function and have it pop all of then, return a new
518list of all their former last elements:
519
520 @tailings = popmany ( \@a, \@b, \@c, \@d );
521
522 sub popmany {
523 my $aref;
524 my @retlist = ();
525 foreach $aref ( @_ ) {
526 push @retlist, pop @$aref;
527 }
528 return @retlist;
529 }
530
531Here's how you might write a function that returns a
532list of keys occurring in all the hashes passed to it:
533
534 @common = inter( \%foo, \%bar, \%joe );
535 sub inter {
536 my ($k, $href, %seen); # locals
537 foreach $href (@_) {
538 while ( $k = each %$href ) {
539 $seen{$k}++;
540 }
541 }
542 return grep { $seen{$_} == @_ } keys %seen;
543 }
544
5f05dabc 545So far, we're using just the normal list return mechanism.
cb1a09d0 546What happens if you want to pass or return a hash? Well,
5f05dabc 547if you're using only one of them, or you don't mind them
cb1a09d0 548concatenating, then the normal calling convention is ok, although
549a little expensive.
550
551Where people get into trouble is here:
552
553 (@a, @b) = func(@c, @d);
554or
555 (%a, %b) = func(%c, %d);
556
5f05dabc 557That syntax simply won't work. It sets just @a or %a and clears the @b or
cb1a09d0 558%b. Plus the function didn't get passed into two separate arrays or
559hashes: it got one long list in @_, as always.
560
561If you can arrange for everyone to deal with this through references, it's
562cleaner code, although not so nice to look at. Here's a function that
563takes two array references as arguments, returning the two array elements
564in order of how many elements they have in them:
565
566 ($aref, $bref) = func(\@c, \@d);
567 print "@$aref has more than @$bref\n";
568 sub func {
569 my ($cref, $dref) = @_;
570 if (@$cref > @$dref) {
571 return ($cref, $dref);
572 } else {
c07a80fd 573 return ($dref, $cref);
cb1a09d0 574 }
575 }
576
577It turns out that you can actually do this also:
578
579 (*a, *b) = func(\@c, \@d);
580 print "@a has more than @b\n";
581 sub func {
582 local (*c, *d) = @_;
583 if (@c > @d) {
584 return (\@c, \@d);
585 } else {
586 return (\@d, \@c);
587 }
588 }
589
590Here we're using the typeglobs to do symbol table aliasing. It's
591a tad subtle, though, and also won't work if you're using my()
5f05dabc 592variables, because only globals (well, and local()s) are in the symbol table.
593
594If you're passing around filehandles, you could usually just use the bare
595typeglob, like *STDOUT, but typeglobs references would be better because
596they'll still work properly under C<use strict 'refs'>. For example:
597
598 splutter(\*STDOUT);
599 sub splutter {
600 my $fh = shift;
601 print $fh "her um well a hmmm\n";
602 }
603
604 $rec = get_rec(\*STDIN);
605 sub get_rec {
606 my $fh = shift;
607 return scalar <$fh>;
608 }
609
610Another way to do this is using *HANDLE{IO}, see L<perlref> for usage
611and caveats.
612
613If you're planning on generating new filehandles, you could do this:
614
615 sub openit {
616 my $name = shift;
617 local *FH;
e05a3a1e 618 return open (FH, $path) ? *FH : undef;
5f05dabc 619 }
620
621Although that will actually produce a small memory leak. See the bottom
622of L<perlfunc/open()> for a somewhat cleaner way using the IO::Handle
623package.
cb1a09d0 624
cb1a09d0 625=head2 Prototypes
626
627As of the 5.002 release of perl, if you declare
628
629 sub mypush (\@@)
630
c07a80fd 631then mypush() takes arguments exactly like push() does. The declaration
632of the function to be called must be visible at compile time. The prototype
5f05dabc 633affects only the interpretation of new-style calls to the function, where
c07a80fd 634new-style is defined as not using the C<&> character. In other words,
635if you call it like a builtin function, then it behaves like a builtin
636function. If you call it like an old-fashioned subroutine, then it
637behaves like an old-fashioned subroutine. It naturally falls out from
638this rule that prototypes have no influence on subroutine references
639like C<\&foo> or on indirect subroutine calls like C<&{$subref}>.
640
641Method calls are not influenced by prototypes either, because the
5f05dabc 642function to be called is indeterminate at compile time, because it depends
c07a80fd 643on inheritance.
cb1a09d0 644
5f05dabc 645Because the intent is primarily to let you define subroutines that work
c07a80fd 646like builtin commands, here are the prototypes for some other functions
647that parse almost exactly like the corresponding builtins.
cb1a09d0 648
649 Declared as Called as
650
651 sub mylink ($$) mylink $old, $new
652 sub myvec ($$$) myvec $var, $offset, 1
653 sub myindex ($$;$) myindex &getstring, "substr"
654 sub mysyswrite ($$$;$) mysyswrite $buf, 0, length($buf) - $off, $off
655 sub myreverse (@) myreverse $a,$b,$c
656 sub myjoin ($@) myjoin ":",$a,$b,$c
657 sub mypop (\@) mypop @array
658 sub mysplice (\@$$@) mysplice @array,@array,0,@pushme
659 sub mykeys (\%) mykeys %{$hashref}
660 sub myopen (*;$) myopen HANDLE, $name
661 sub mypipe (**) mypipe READHANDLE, WRITEHANDLE
662 sub mygrep (&@) mygrep { /foo/ } $a,$b,$c
663 sub myrand ($) myrand 42
664 sub mytime () mytime
665
c07a80fd 666Any backslashed prototype character represents an actual argument
6e47f808 667that absolutely must start with that character. The value passed
668to the subroutine (as part of C<@_>) will be a reference to the
669actual argument given in the subroutine call, obtained by applying
670C<\> to that argument.
c07a80fd 671
672Unbackslashed prototype characters have special meanings. Any
673unbackslashed @ or % eats all the rest of the arguments, and forces
674list context. An argument represented by $ forces scalar context. An
675& requires an anonymous subroutine, which, if passed as the first
676argument, does not require the "sub" keyword or a subsequent comma. A
677* does whatever it has to do to turn the argument into a reference to a
678symbol table entry.
679
680A semicolon separates mandatory arguments from optional arguments.
681(It is redundant before @ or %.)
cb1a09d0 682
c07a80fd 683Note how the last three examples above are treated specially by the parser.
cb1a09d0 684mygrep() is parsed as a true list operator, myrand() is parsed as a
685true unary operator with unary precedence the same as rand(), and
5f05dabc 686mytime() is truly without arguments, just like time(). That is, if you
cb1a09d0 687say
688
689 mytime +2;
690
691you'll get mytime() + 2, not mytime(2), which is how it would be parsed
692without the prototype.
693
694The interesting thing about & is that you can generate new syntax with it:
695
6d28dffb 696 sub try (&@) {
cb1a09d0 697 my($try,$catch) = @_;
698 eval { &$try };
699 if ($@) {
700 local $_ = $@;
701 &$catch;
702 }
703 }
55497cff 704 sub catch (&) { $_[0] }
cb1a09d0 705
706 try {
707 die "phooey";
708 } catch {
709 /phooey/ and print "unphooey\n";
710 };
711
712That prints "unphooey". (Yes, there are still unresolved
713issues having to do with the visibility of @_. I'm ignoring that
714question for the moment. (But note that if we make @_ lexically
715scoped, those anonymous subroutines can act like closures... (Gee,
5f05dabc 716is this sounding a little Lispish? (Never mind.))))
cb1a09d0 717
718And here's a reimplementation of grep:
719
720 sub mygrep (&@) {
721 my $code = shift;
722 my @result;
723 foreach $_ (@_) {
6e47f808 724 push(@result, $_) if &$code;
cb1a09d0 725 }
726 @result;
727 }
a0d0e21e 728
cb1a09d0 729Some folks would prefer full alphanumeric prototypes. Alphanumerics have
730been intentionally left out of prototypes for the express purpose of
731someday in the future adding named, formal parameters. The current
732mechanism's main goal is to let module writers provide better diagnostics
733for module users. Larry feels the notation quite understandable to Perl
734programmers, and that it will not intrude greatly upon the meat of the
735module, nor make it harder to read. The line noise is visually
736encapsulated into a small pill that's easy to swallow.
737
738It's probably best to prototype new functions, not retrofit prototyping
739into older ones. That's because you must be especially careful about
740silent impositions of differing list versus scalar contexts. For example,
741if you decide that a function should take just one parameter, like this:
742
743 sub func ($) {
744 my $n = shift;
745 print "you gave me $n\n";
746 }
747
748and someone has been calling it with an array or expression
749returning a list:
750
751 func(@foo);
752 func( split /:/ );
753
754Then you've just supplied an automatic scalar() in front of their
755argument, which can be more than a bit surprising. The old @foo
756which used to hold one thing doesn't get passed in. Instead,
5f05dabc 757the func() now gets passed in 1, that is, the number of elements
cb1a09d0 758in @foo. And the split() gets called in a scalar context and
759starts scribbling on your @_ parameter list.
760
5f05dabc 761This is all very powerful, of course, and should be used only in moderation
cb1a09d0 762to make the world a better place.
44a8e56a 763
764=head2 Constant Functions
765
766Functions with a prototype of C<()> are potential candidates for
767inlining. If the result after optimization and constant folding is a
768constant then it will be used in place of new-style calls to the
769function. Old-style calls (that is, calls made using C<&>) are not
770affected.
771
772All of the following functions would be inlined.
773
774 sub PI () { 3.14159 }
775 sub ST_DEV () { 0 }
776 sub ST_INO () { 1 }
777
778 sub FLAG_FOO () { 1 << 8 }
779 sub FLAG_BAR () { 1 << 9 }
780 sub FLAG_MASK () { FLAG_FOO | FLAG_BAR }
781
782 sub OPT_BAZ () { 1 }
783 sub BAZ_VAL () {
784 if (OPT_BAZ) {
785 return 23;
786 }
787 else {
788 return 42;
789 }
790 }
cb1a09d0 791
4cee8e80 792If you redefine a subroutine which was eligible for inlining you'll get
793a mandatory warning. (You can use this warning to tell whether or not a
794particular subroutine is considered constant.) The warning is
795considered severe enough not to be optional because previously compiled
796invocations of the function will still be using the old value of the
797function. If you need to be able to redefine the subroutine you need to
798ensure that it isn't inlined, either by dropping the C<()> prototype
799(which changes the calling semantics, so beware) or by thwarting the
800inlining mechanism in some other way, such as
801
802 my $dummy;
803 sub not_inlined () {
804 $dummy || 23
805 }
806
cb1a09d0 807=head2 Overriding Builtin Functions
a0d0e21e 808
5f05dabc 809Many builtin functions may be overridden, though this should be tried
810only occasionally and for good reason. Typically this might be
a0d0e21e 811done by a package attempting to emulate missing builtin functionality
812on a non-Unix system.
813
5f05dabc 814Overriding may be done only by importing the name from a
a0d0e21e 815module--ordinary predeclaration isn't good enough. However, the
5f05dabc 816C<subs> pragma (compiler directive) lets you, in effect, pre-declare subs
a0d0e21e 817via the import syntax, and these names may then override the builtin ones:
818
819 use subs 'chdir', 'chroot', 'chmod', 'chown';
820 chdir $somewhere;
821 sub chdir { ... }
822
823Library modules should not in general export builtin names like "open"
5f05dabc 824or "chdir" as part of their default @EXPORT list, because these may
a0d0e21e 825sneak into someone else's namespace and change the semantics unexpectedly.
826Instead, if the module adds the name to the @EXPORT_OK list, then it's
827possible for a user to import the name explicitly, but not implicitly.
828That is, they could say
829
830 use Module 'open';
831
832and it would import the open override, but if they said
833
834 use Module;
835
836they would get the default imports without the overrides.
837
838=head2 Autoloading
839
840If you call a subroutine that is undefined, you would ordinarily get an
841immediate fatal error complaining that the subroutine doesn't exist.
842(Likewise for subroutines being used as methods, when the method
843doesn't exist in any of the base classes of the class package.) If,
844however, there is an C<AUTOLOAD> subroutine defined in the package or
845packages that were searched for the original subroutine, then that
846C<AUTOLOAD> subroutine is called with the arguments that would have been
847passed to the original subroutine. The fully qualified name of the
848original subroutine magically appears in the $AUTOLOAD variable in the
849same package as the C<AUTOLOAD> routine. The name is not passed as an
850ordinary argument because, er, well, just because, that's why...
851
852Most C<AUTOLOAD> routines will load in a definition for the subroutine in
853question using eval, and then execute that subroutine using a special
854form of "goto" that erases the stack frame of the C<AUTOLOAD> routine
855without a trace. (See the standard C<AutoLoader> module, for example.)
856But an C<AUTOLOAD> routine can also just emulate the routine and never
cb1a09d0 857define it. For example, let's pretend that a function that wasn't defined
858should just call system() with those arguments. All you'd do is this:
859
860 sub AUTOLOAD {
861 my $program = $AUTOLOAD;
862 $program =~ s/.*:://;
863 system($program, @_);
864 }
865 date();
6d28dffb 866 who('am', 'i');
cb1a09d0 867 ls('-l');
868
5f05dabc 869In fact, if you pre-declare the functions you want to call that way, you don't
cb1a09d0 870even need the parentheses:
871
872 use subs qw(date who ls);
873 date;
874 who "am", "i";
875 ls -l;
876
877A more complete example of this is the standard Shell module, which
a0d0e21e 878can treat undefined subroutine calls as calls to Unix programs.
879
cb1a09d0 880Mechanisms are available for modules writers to help split the modules
6d28dffb 881up into autoloadable files. See the standard AutoLoader module
882described in L<AutoLoader> and in L<AutoSplit>, the standard
883SelfLoader modules in L<SelfLoader>, and the document on adding C
884functions to perl code in L<perlxs>.
cb1a09d0 885
886=head1 SEE ALSO
a0d0e21e 887
cb1a09d0 888See L<perlref> for more on references. See L<perlxs> if you'd
889like to learn about calling C subroutines from perl. See
890L<perlmod> to learn about bundling up your functions in
891separate files.