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