home *** CD-ROM | disk | FTP | other *** search
/ Acorn User 10 / AU_CD10.iso / Updates / Perl / Non-RPC / Docs / perlsub < prev    next >
Text File  |  1999-04-17  |  48KB  |  1,303 lines

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