home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / perl_pod.zip / perlsub.pod < prev    next >
Text File  |  1997-11-25  |  35KB  |  954 lines

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