3 perlsub - Perl subroutines
7 To declare subroutines:
9 sub NAME; # A "forward" declaration.
10 sub NAME(PROTO); # ditto, but with prototypes
12 sub NAME BLOCK # A declaration and a definition.
13 sub NAME(PROTO) BLOCK # ditto, but with prototypes
15 To define an anonymous subroutine at runtime:
19 To import subroutines:
21 use PACKAGE qw(NAME1 NAME2 NAME3);
25 NAME(LIST); # & is optional with parentheses.
26 NAME LIST; # Parentheses optional if pre-declared/imported.
27 &NAME; # Passes current @_ to subroutine.
31 Like many languages, Perl provides for user-defined subroutines. These
32 may be located anywhere in the main program, loaded in from other files
33 via the C<do>, C<require>, or C<use> keywords, or even generated on the
34 fly using C<eval> or anonymous subroutines (closures). You can even call
35 a function indirectly using a variable containing its name or a CODE reference
36 to it, as in C<$var = \&function>.
38 The Perl model for function call and return values is simple: all
39 functions are passed as parameters one single flat list of scalars, and
40 all functions likewise return to their caller one single flat list of
41 scalars. Any arrays or hashes in these call and return lists will
42 collapse, losing their identities--but you may always use
43 pass-by-reference instead to avoid this. Both call and return lists may
44 contain as many or as few scalar elements as you'd like. (Often a
45 function without an explicit return statement is called a subroutine, but
46 there's really no difference from the language's perspective.)
48 Any arguments passed to the routine come in as the array @_. Thus if you
49 called a function with two arguments, those would be stored in C<$_[0]>
50 and C<$_[1]>. The array @_ is a local array, but its values are implicit
51 references (predating L<perlref>) to the actual scalar parameters. What
52 this means in practice is that when you explicitly modify C<$_[0]> et al.,
53 you will be changing the actual arguments. As a result, all arguments
54 to functions are treated as lvalues. Any hash or array elements that are
55 passed to functions will get created if they do not exist (irrespective
56 of whether the function does modify the contents of C<@_>). This is
57 frequently a source of surprise. See L<perltrap> for an example.
59 The return value of the subroutine is the value of the last expression
60 evaluated. Alternatively, a return statement may be used to specify the
61 returned value and exit the subroutine. If you return one or more arrays
62 and/or hashes, these will be flattened together into one large
63 indistinguishable list.
65 Perl does not have named formal parameters, but in practice all you do is
66 assign to a my() list of these. Any variables you use in the function
67 that aren't declared private are global variables. For the gory details
68 on creating private variables, see
69 L<"Private Variables via my()"> and L<"Temporary Values via local()">.
70 To create protected environments for a set of functions in a separate
71 package (and probably a separate file), see L<perlmod/"Packages">.
78 $max = $foo if $max < $foo;
82 $bestday = max($mon,$tue,$wed,$thu,$fri);
86 # get a line, combining continuation lines
87 # that start with whitespace
90 $thisline = $lookahead; # GLOBAL VARIABLES!!
91 LINE: while ($lookahead = <STDIN>) {
92 if ($lookahead =~ /^[ \t]/) {
93 $thisline .= $lookahead;
102 $lookahead = <STDIN>; # get first line
103 while ($_ = get_line()) {
107 Use array assignment to a local list to name your formal arguments:
110 my($key, $value) = @_;
111 $Foo{$key} = $value unless $Foo{$key};
114 This also has the effect of turning call-by-reference into call-by-value,
115 because the assignment copies the values. Otherwise a function is free to
116 do in-place modifications of @_ and change its caller's values.
118 upcase_in($v1, $v2); # this changes $v1 and $v2
120 for (@_) { tr/a-z/A-Z/ }
123 You aren't allowed to modify constants in this way, of course. If an
124 argument were actually literal and you tried to change it, you'd take a
125 (presumably fatal) exception. For example, this won't work:
127 upcase_in("frederick");
129 It would be much safer if the upcase_in() function
130 were written to return a copy of its parameters instead
131 of changing them in place:
133 ($v3, $v4) = upcase($v1, $v2); # this doesn't
136 for (@parms) { tr/a-z/A-Z/ }
137 # wantarray checks if we were called in list context
138 return wantarray ? @parms : $parms[0];
141 Notice how this (unprototyped) function doesn't care whether it was passed
142 real scalars or arrays. Perl will see everything as one big long flat @_
143 parameter list. This is one of the ways where Perl's simple
144 argument-passing style shines. The upcase() function would work perfectly
145 well without changing the upcase() definition even if we fed it things
148 @newlist = upcase(@list1, @list2);
149 @newlist = upcase( split /:/, $var );
151 Do not, however, be tempted to do this:
153 (@a, @b) = upcase(@list1, @list2);
155 Because like its flat incoming parameter list, the return list is also
156 flat. So all you have managed to do here is stored everything in @a and
157 made @b an empty list. See L</"Pass by Reference"> for alternatives.
159 A subroutine may be called using the "&" prefix. The "&" is optional
160 in modern Perls, and so are the parentheses if the subroutine has been
161 pre-declared. (Note, however, that the "&" is I<NOT> optional when
162 you're just naming the subroutine, such as when it's used as an
163 argument to defined() or undef(). Nor is it optional when you want to
164 do an indirect subroutine call with a subroutine name or reference
165 using the C<&$subref()> or C<&{$subref}()> constructs. See L<perlref>
168 Subroutines may be called recursively. If a subroutine is called using
169 the "&" form, the argument list is optional, and if omitted, no @_ array is
170 set up for the subroutine: the @_ array at the time of the call is
171 visible to subroutine instead. This is an efficiency mechanism that
172 new users may wish to avoid.
174 &foo(1,2,3); # pass three arguments
175 foo(1,2,3); # the same
177 foo(); # pass a null list
180 &foo; # foo() get current args, like foo(@_) !!
181 foo; # like foo() IFF sub foo pre-declared, else "foo"
183 Not only does the "&" form make the argument list optional, but it also
184 disables any prototype checking on the arguments you do provide. This
185 is partly for historical reasons, and partly for having a convenient way
186 to cheat if you know what you're doing. See the section on Prototypes below.
188 =head2 Private Variables via my()
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
197 A "my" declares the listed variables to be confined (lexically) to the
198 enclosing block, conditional (C<if/unless/elsif/else>), loop
199 (C<for/foreach/while/until/continue>), subroutine, C<eval>, or
200 C<do/require/use>'d file. If more than one value is listed, the list
201 must be placed in parentheses. All listed elements must be legal lvalues.
202 Only alphanumeric identifiers may be lexically scoped--magical
203 builtins like $/ must currently be localized with "local" instead.
205 Unlike dynamic variables created by the "local" statement, lexical
206 variables declared with "my" are totally hidden from the outside world,
207 including any called subroutines (even if it's the same subroutine called
208 from itself or elsewhere--every call gets its own copy).
210 (An eval(), however, can see the lexical variables of the scope it is
211 being evaluated in so long as the names aren't hidden by declarations within
212 the eval() itself. See L<perlref>.)
214 The parameter list to my() may be assigned to if desired, which allows you
215 to initialize your variables. (If no initializer is given for a
216 particular variable, it is created with the undefined value.) Commonly
217 this is used to name the parameters to a subroutine. Examples:
219 $arg = "fred"; # "global" variable
221 print "$arg thinks the root is $n\n";
222 fred thinks the root is 3
225 my $arg = shift; # name doesn't matter
230 The "my" is simply a modifier on something you might assign to. So when
231 you do assign to the variables in its argument list, the "my" doesn't
232 change whether those variables is viewed as a scalar or an array. So
237 both supply a list context to the right-hand side, while
241 supplies a scalar context. But the following declares only one variable:
245 That has the same effect as
250 The declared variable is not introduced (is not visible) until after
251 the current statement. Thus,
255 can be used to initialize the new $x with the value of the old $x, and
258 my $x = 123 and $x == 123
260 is false unless the old $x happened to have the value 123.
262 Lexical scopes of control structures are not bounded precisely by the
263 braces that delimit their controlled blocks; control expressions are
264 part of the scope, too. Thus in the loop
266 while (my $line = <>) {
272 the scope of $line extends from its declaration throughout the rest of
273 the loop construct (including the C<continue> clause), but not beyond
274 it. Similarly, in the conditional
276 if ((my $answer = <STDIN>) =~ /^yes$/i) {
278 } elsif ($answer =~ /^no$/i) {
282 die "'$answer' is neither 'yes' nor 'no'";
285 the scope of $answer extends from its declaration throughout the rest
286 of the conditional (including C<elsif> and C<else> clauses, if any),
289 (None of the foregoing applies to C<if/unless> or C<while/until>
290 modifiers appended to simple statements. Such modifiers are not
291 control structures and have no effect on scoping.)
293 The C<foreach> loop defaults to scoping its index variable dynamically
294 (in the manner of C<local>; see below). However, if the index
295 variable is prefixed with the keyword "my", then it is lexically
296 scoped instead. Thus in the loop
298 for my $i (1, 2, 3) {
302 the scope of $i extends to the end of the loop, but not beyond it, and
303 so the value of $i is unavailable in some_function().
305 Some users may wish to encourage the use of lexically scoped variables.
306 As an aid to catching implicit references to package variables,
311 then any variable reference from there to the end of the enclosing
312 block must either refer to a lexical variable, or must be fully
313 qualified with the package name. A compilation error results
314 otherwise. An inner block may countermand this with S<"no strict 'vars'">.
316 A my() has both a compile-time and a run-time effect. At compile time,
317 the compiler takes notice of it; the principle usefulness of this is to
318 quiet C<use strict 'vars'>. The actual initialization doesn't happen
319 until run time, so gets executed every time through a loop.
321 Variables declared with "my" are not part of any package and are therefore
322 never fully qualified with the package name. In particular, you're not
323 allowed to try to make a package variable (or other global) lexical:
325 my $pack::var; # ERROR! Illegal syntax
326 my $_; # also illegal (currently)
328 In fact, a dynamic variable (also known as package or global variables)
329 are still accessible using the fully qualified :: notation even while a
330 lexical of the same name is also visible:
335 print "$x and $::x\n";
337 That will print out 20 and 10.
339 You may declare "my" variables at the outermost scope of a file to
340 hide any such identifiers totally from the outside world. This is similar
341 to C's static variables at the file level. To do this with a subroutine
342 requires the use of a closure (anonymous function). If a block (such as
343 an eval(), function, or C<package>) wants to create a private subroutine
344 that cannot be called from outside that block, it can declare a lexical
345 variable containing an anonymous sub reference:
347 my $secret_version = '1.001-beta';
348 my $secret_sub = sub { print $secret_version };
351 As long as the reference is never returned by any function within the
352 module, no outside module can see the subroutine, because its name is not in
353 any package's symbol table. Remember that it's not I<REALLY> called
354 $some_pack::secret_version or anything; it's just $secret_version,
355 unqualified and unqualifiable.
357 This does not work with object methods, however; all object methods have
358 to be in the symbol table of some package to be found.
360 Just because the lexical variable is lexically (also called statically)
361 scoped doesn't mean that within a function it works like a C static. It
362 normally works more like a C auto. But here's a mechanism for giving a
363 function private variables with both lexical scoping and a static
364 lifetime. If you do want to create something like C's static variables,
365 just enclose the whole function in an extra block, and put the
366 static variable outside the function but in the block.
371 return ++$secret_val;
374 # $secret_val now becomes unreachable by the outside
375 # world, but retains its value between calls to gimme_another
377 If this function is being sourced in from a separate file
378 via C<require> or C<use>, then this is probably just fine. If it's
379 all in the main program, you'll need to arrange for the my()
380 to be executed early, either by putting the whole block above
381 your pain program, or more likely, placing merely a BEGIN
382 sub around it to make sure it gets executed before your program
388 return ++$secret_val;
392 See L<perlrun> about the BEGIN function.
394 =head2 Temporary Values via local()
396 B<NOTE>: In general, you should be using "my" instead of "local", because
397 it's faster and safer. Exceptions to this include the global punctuation
398 variables, filehandles and formats, and direct manipulation of the Perl
399 symbol table itself. Format variables often use "local" though, as do
400 other variables whose current value must be visible to called
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
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
416 A local() modifies its listed variables to be local to the enclosing
417 block, (or subroutine, C<eval{}>, or C<do>) and I<any called from
418 within that block>. A local() just gives temporary values to global
419 (meaning package) variables. This is known as dynamic scoping. Lexical
420 scoping is done with "my", which works more like C's auto declarations.
422 If more than one variable is given to local(), they must be placed in
423 parentheses. All listed elements must be legal lvalues. This operator works
424 by saving the current values of those variables in its argument list on a
425 hidden stack and restoring them upon exiting the block, subroutine, or
426 eval. This means that called subroutines can also reference the local
427 variable, but not the global one. The argument list may be assigned to if
428 desired, which allows you to initialize your local variables. (If no
429 initializer is given for a particular variable, it is created with an
430 undefined value.) Commonly this is used to name the parameters to a
431 subroutine. Examples:
436 # assume this function uses global %digits hash
439 # now temporarily add to %digits hash
441 # (NOTE: not claiming this is efficient!)
442 local %digits = (%digits, 't' => 10, 'e' => 11);
443 parse_num(); # parse_num gets this new %digits!
445 # old %digits restored here
447 Because local() is a run-time command, it gets executed every time
448 through a loop. In releases of Perl previous to 5.0, this used more stack
449 storage each time until the loop was exited. Perl now reclaims the space
450 each time through, but it's still more efficient to declare your variables
453 A local is simply a modifier on an lvalue expression. When you assign to
454 a localized variable, the local doesn't change whether its list is viewed
455 as a scalar or an array. So
457 local($foo) = <STDIN>;
458 local @FOO = <STDIN>;
460 both supply a list context to the right-hand side, while
462 local $foo = <STDIN>;
464 supplies a scalar context.
466 =head2 Passing Symbol Table Entries (typeglobs)
468 [Note: The mechanism described in this section was originally the only
469 way to simulate pass-by-reference in older versions of Perl. While it
470 still works fine in modern versions, the new reference mechanism is
471 generally easier to work with. See below.]
473 Sometimes you don't want to pass the value of an array to a subroutine
474 but rather the name of it, so that the subroutine can modify the global
475 copy of it rather than working with a local copy. In perl you can
476 refer to all objects of a particular name by prefixing the name
477 with a star: C<*foo>. This is often known as a "typeglob", because the
478 star on the front can be thought of as a wildcard match for all the
479 funny prefix characters on variables and subroutines and such.
481 When evaluated, the typeglob produces a scalar value that represents
482 all the objects of that name, including any filehandle, format, or
483 subroutine. When assigned to, it causes the name mentioned to refer to
484 whatever "*" value was assigned to it. Example:
487 local(*someary) = @_;
488 foreach $elem (@someary) {
495 Note that scalars are already passed by reference, so you can modify
496 scalar arguments without using this mechanism by referring explicitly
497 to C<$_[0]> etc. You can modify all the elements of an array by passing
498 all the elements as scalars, but you have to use the * mechanism (or
499 the equivalent reference mechanism) to push, pop, or change the size of
500 an array. It will certainly be faster to pass the typeglob (or reference).
502 Even if you don't want to modify an array, this mechanism is useful for
503 passing multiple arrays in a single LIST, because normally the LIST
504 mechanism will merge all the array values so that you can't extract out
505 the individual arrays. For more on typeglobs, see
506 L<perldata/"Typeglobs and FileHandles">.
508 =head2 Pass by Reference
510 If you want to pass more than one array or hash into a function--or
511 return them from it--and have them maintain their integrity, then
512 you're going to have to use an explicit pass-by-reference. Before you
513 do that, you need to understand references as detailed in L<perlref>.
514 This section may not make much sense to you otherwise.
516 Here are a few simple examples. First, let's pass in several
517 arrays to a function and have it pop all of then, return a new
518 list of all their former last elements:
520 @tailings = popmany ( \@a, \@b, \@c, \@d );
525 foreach $aref ( @_ ) {
526 push @retlist, pop @$aref;
531 Here's how you might write a function that returns a
532 list of keys occurring in all the hashes passed to it:
534 @common = inter( \%foo, \%bar, \%joe );
536 my ($k, $href, %seen); # locals
538 while ( $k = each %$href ) {
542 return grep { $seen{$_} == @_ } keys %seen;
545 So far, we're using just the normal list return mechanism.
546 What happens if you want to pass or return a hash? Well,
547 if you're using only one of them, or you don't mind them
548 concatenating, then the normal calling convention is ok, although
551 Where people get into trouble is here:
553 (@a, @b) = func(@c, @d);
555 (%a, %b) = func(%c, %d);
557 That syntax simply won't work. It sets just @a or %a and clears the @b or
558 %b. Plus the function didn't get passed into two separate arrays or
559 hashes: it got one long list in @_, as always.
561 If you can arrange for everyone to deal with this through references, it's
562 cleaner code, although not so nice to look at. Here's a function that
563 takes two array references as arguments, returning the two array elements
564 in order of how many elements they have in them:
566 ($aref, $bref) = func(\@c, \@d);
567 print "@$aref has more than @$bref\n";
569 my ($cref, $dref) = @_;
570 if (@$cref > @$dref) {
571 return ($cref, $dref);
573 return ($dref, $cref);
577 It turns out that you can actually do this also:
579 (*a, *b) = func(\@c, \@d);
580 print "@a has more than @b\n";
590 Here we're using the typeglobs to do symbol table aliasing. It's
591 a tad subtle, though, and also won't work if you're using my()
592 variables, because only globals (well, and local()s) are in the symbol table.
594 If you're passing around filehandles, you could usually just use the bare
595 typeglob, like *STDOUT, but typeglobs references would be better because
596 they'll still work properly under C<use strict 'refs'>. For example:
601 print $fh "her um well a hmmm\n";
604 $rec = get_rec(\*STDIN);
610 Another way to do this is using *HANDLE{IO}, see L<perlref> for usage
613 If you're planning on generating new filehandles, you could do this:
618 return open (FH, $path) ? *FH : undef;
621 Although that will actually produce a small memory leak. See the bottom
622 of L<perlfunc/open()> for a somewhat cleaner way using the IO::Handle
627 As of the 5.002 release of perl, if you declare
631 then mypush() takes arguments exactly like push() does. The declaration
632 of the function to be called must be visible at compile time. The prototype
633 affects only the interpretation of new-style calls to the function, where
634 new-style is defined as not using the C<&> character. In other words,
635 if you call it like a builtin function, then it behaves like a builtin
636 function. If you call it like an old-fashioned subroutine, then it
637 behaves like an old-fashioned subroutine. It naturally falls out from
638 this rule that prototypes have no influence on subroutine references
639 like C<\&foo> or on indirect subroutine calls like C<&{$subref}>.
641 Method calls are not influenced by prototypes either, because the
642 function to be called is indeterminate at compile time, because it depends
645 Because the intent is primarily to let you define subroutines that work
646 like builtin commands, here are the prototypes for some other functions
647 that parse almost exactly like the corresponding builtins.
649 Declared as Called as
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
666 Any backslashed prototype character represents an actual argument
667 that absolutely must start with that character. The value passed
668 to the subroutine (as part of C<@_>) will be a reference to the
669 actual argument given in the subroutine call, obtained by applying
670 C<\> to that argument.
672 Unbackslashed prototype characters have special meanings. Any
673 unbackslashed @ or % eats all the rest of the arguments, and forces
674 list context. An argument represented by $ forces scalar context. An
675 & requires an anonymous subroutine, which, if passed as the first
676 argument, 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
680 A semicolon separates mandatory arguments from optional arguments.
681 (It is redundant before @ or %.)
683 Note how the last three examples above are treated specially by the parser.
684 mygrep() is parsed as a true list operator, myrand() is parsed as a
685 true unary operator with unary precedence the same as rand(), and
686 mytime() is truly without arguments, just like time(). That is, if you
691 you'll get mytime() + 2, not mytime(2), which is how it would be parsed
692 without the prototype.
694 The interesting thing about & is that you can generate new syntax with it:
697 my($try,$catch) = @_;
704 sub catch (&) { $_[0] }
709 /phooey/ and print "unphooey\n";
712 That prints "unphooey". (Yes, there are still unresolved
713 issues having to do with the visibility of @_. I'm ignoring that
714 question for the moment. (But note that if we make @_ lexically
715 scoped, those anonymous subroutines can act like closures... (Gee,
716 is this sounding a little Lispish? (Never mind.))))
718 And here's a reimplementation of grep:
724 push(@result, $_) if &$code;
729 Some folks would prefer full alphanumeric prototypes. Alphanumerics have
730 been intentionally left out of prototypes for the express purpose of
731 someday in the future adding named, formal parameters. The current
732 mechanism's main goal is to let module writers provide better diagnostics
733 for module users. Larry feels the notation quite understandable to Perl
734 programmers, and that it will not intrude greatly upon the meat of the
735 module, nor make it harder to read. The line noise is visually
736 encapsulated into a small pill that's easy to swallow.
738 It's probably best to prototype new functions, not retrofit prototyping
739 into older ones. That's because you must be especially careful about
740 silent impositions of differing list versus scalar contexts. For example,
741 if you decide that a function should take just one parameter, like this:
745 print "you gave me $n\n";
748 and someone has been calling it with an array or expression
754 Then you've just supplied an automatic scalar() in front of their
755 argument, which can be more than a bit surprising. The old @foo
756 which used to hold one thing doesn't get passed in. Instead,
757 the func() now gets passed in 1, that is, the number of elements
758 in @foo. And the split() gets called in a scalar context and
759 starts scribbling on your @_ parameter list.
761 This is all very powerful, of course, and should be used only in moderation
762 to make the world a better place.
764 =head2 Constant Functions
766 Functions with a prototype of C<()> are potential candidates for
767 inlining. If the result after optimization and constant folding is a
768 constant then it will be used in place of new-style calls to the
769 function. Old-style calls (that is, calls made using C<&>) are not
772 All of the following functions would be inlined.
774 sub PI () { 3.14159 }
778 sub FLAG_FOO () { 1 << 8 }
779 sub FLAG_BAR () { 1 << 9 }
780 sub FLAG_MASK () { FLAG_FOO | FLAG_BAR }
792 If you redefine a subroutine which was eligible for inlining you'll get
793 a mandatory warning. (You can use this warning to tell whether or not a
794 particular subroutine is considered constant.) The warning is
795 considered severe enough not to be optional because previously compiled
796 invocations of the function will still be using the old value of the
797 function. If you need to be able to redefine the subroutine you need to
798 ensure that it isn't inlined, either by dropping the C<()> prototype
799 (which changes the calling semantics, so beware) or by thwarting the
800 inlining mechanism in some other way, such as
807 =head2 Overriding Builtin Functions
809 Many builtin functions may be overridden, though this should be tried
810 only occasionally and for good reason. Typically this might be
811 done by a package attempting to emulate missing builtin functionality
812 on a non-Unix system.
814 Overriding may be done only by importing the name from a
815 module--ordinary predeclaration isn't good enough. However, the
816 C<subs> pragma (compiler directive) lets you, in effect, pre-declare subs
817 via the import syntax, and these names may then override the builtin ones:
819 use subs 'chdir', 'chroot', 'chmod', 'chown';
823 Library modules should not in general export builtin names like "open"
824 or "chdir" as part of their default @EXPORT list, because these may
825 sneak into someone else's namespace and change the semantics unexpectedly.
826 Instead, if the module adds the name to the @EXPORT_OK list, then it's
827 possible for a user to import the name explicitly, but not implicitly.
828 That is, they could say
832 and it would import the open override, but if they said
836 they would get the default imports without the overrides.
840 If you call a subroutine that is undefined, you would ordinarily get an
841 immediate fatal error complaining that the subroutine doesn't exist.
842 (Likewise for subroutines being used as methods, when the method
843 doesn't exist in any of the base classes of the class package.) If,
844 however, there is an C<AUTOLOAD> subroutine defined in the package or
845 packages that were searched for the original subroutine, then that
846 C<AUTOLOAD> subroutine is called with the arguments that would have been
847 passed to the original subroutine. The fully qualified name of the
848 original subroutine magically appears in the $AUTOLOAD variable in the
849 same package as the C<AUTOLOAD> routine. The name is not passed as an
850 ordinary argument because, er, well, just because, that's why...
852 Most C<AUTOLOAD> routines will load in a definition for the subroutine in
853 question using eval, and then execute that subroutine using a special
854 form of "goto" that erases the stack frame of the C<AUTOLOAD> routine
855 without a trace. (See the standard C<AutoLoader> module, for example.)
856 But an C<AUTOLOAD> routine can also just emulate the routine and never
857 define it. For example, let's pretend that a function that wasn't defined
858 should just call system() with those arguments. All you'd do is this:
861 my $program = $AUTOLOAD;
862 $program =~ s/.*:://;
863 system($program, @_);
869 In fact, if you pre-declare the functions you want to call that way, you don't
870 even need the parentheses:
872 use subs qw(date who ls);
877 A more complete example of this is the standard Shell module, which
878 can treat undefined subroutine calls as calls to Unix programs.
880 Mechanisms are available for modules writers to help split the modules
881 up into autoloadable files. See the standard AutoLoader module
882 described in L<AutoLoader> and in L<AutoSplit>, the standard
883 SelfLoader modules in L<SelfLoader>, and the document on adding C
884 functions to perl code in L<perlxs>.
888 See L<perlref> for more on references. See L<perlxs> if you'd
889 like to learn about calling C subroutines from perl. See
890 L<perlmod> to learn about bundling up your functions in