home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / perl501m.zip / pod / perlsub.pod < prev    next >
Text File  |  1995-03-16  |  8KB  |  211 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 BLOCK # A declaration and a definition.
  11.  
  12. To define an anonymous subroutine at runtime:
  13.  
  14.     $subref = sub BLOCK;
  15.  
  16. To import subroutines:
  17.  
  18.     use PACKAGE qw(NAME1 NAME2 NAME3);
  19.  
  20. To call subroutines:
  21.  
  22.     &NAME       # Passes current @_ to subroutine.
  23.     &NAME(LIST);   # Parens required with & form.
  24.     NAME(LIST);       # & is optional with parens.
  25.     NAME LIST;       # Parens optional if predeclared/imported.
  26.  
  27. =head1 DESCRIPTION
  28.  
  29. Any arguments passed to the routine come in as array @_, that is
  30. ($_[0], $_[1], ...).  The array @_ is a local array, but its values are
  31. references to the actual scalar parameters.  The return value of the
  32. subroutine is the value of the last expression evaluated, and can be
  33. either an array value or a scalar value.  Alternatively, a return
  34. statement may be used to specify the returned value and exit the
  35. subroutine.  To create local variables see the local() and my()
  36. operators.
  37.  
  38. A subroutine may be called using the "&" prefix.  The "&" is optional in Perl
  39. 5, and so are the parens if the subroutine has been predeclared.
  40. (Note, however, that the "&" is I<NOT> optional when you're just naming the
  41. subroutine, such as when it's used as an argument to defined() or
  42. undef().  Nor is it optional when you want to do an indirect subroutine
  43. call with a subroutine name or reference using the C<&$subref()> or
  44. C<&{$subref}()> constructs.  See L<perlref> for more on that.)
  45.  
  46. Example:
  47.  
  48.     sub MAX {
  49.     my $max = pop(@_);
  50.     foreach $foo (@_) {
  51.         $max = $foo if $max < $foo;
  52.     }
  53.     $max;
  54.     }
  55.  
  56.     ...
  57.     $bestday = &MAX($mon,$tue,$wed,$thu,$fri);
  58.  
  59. Example:
  60.  
  61.     # get a line, combining continuation lines
  62.     #  that start with whitespace
  63.  
  64.     sub get_line {
  65.     $thisline = $lookahead;
  66.     LINE: while ($lookahead = <STDIN>) {
  67.         if ($lookahead =~ /^[ \t]/) {
  68.         $thisline .= $lookahead;
  69.         }
  70.         else {
  71.         last LINE;
  72.         }
  73.     }
  74.     $thisline;
  75.     }
  76.  
  77.     $lookahead = <STDIN>;    # get first line
  78.     while ($_ = get_line()) {
  79.     ...
  80.     }
  81.  
  82. Use array assignment to a local list to name your formal arguments:
  83.  
  84.     sub maybeset {
  85.     my($key, $value) = @_;
  86.     $foo{$key} = $value unless $foo{$key};
  87.     }
  88.  
  89. This also has the effect of turning call-by-reference into
  90. call-by-value, since the assignment copies the values.
  91.  
  92. Subroutines may be called recursively.  If a subroutine is called using
  93. the "&" form, the argument list is optional.  If omitted, no @_ array is
  94. set up for the subroutine; the @_ array at the time of the call is
  95. visible to subroutine instead.
  96.  
  97.     &foo(1,2,3);    # pass three arguments
  98.     foo(1,2,3);        # the same
  99.  
  100.     foo();        # pass a null list
  101.     &foo();        # the same
  102.     &foo;        # pass no arguments--more efficient
  103.  
  104. If a module wants to create a private subroutine that cannot be called
  105. from outside the module, it can declare a lexical variable containing
  106. an anonymous sub reference:
  107.  
  108.     my $subref = sub { ... }
  109.     &$subref(1,2,3);
  110.  
  111. As long as the reference is never returned by any function within the module,
  112. no outside module can see the subroutine, since its name is not in any
  113. package's symbol table.
  114.  
  115. =head2 Passing Symbol Table Entries
  116.  
  117. [Note:  The mechanism described in this section works fine in Perl 5, but
  118. the new reference mechanism is generally easier to work with.  See L<perlref>.]
  119.  
  120. Sometimes you don't want to pass the value of an array to a subroutine
  121. but rather the name of it, so that the subroutine can modify the global
  122. copy of it rather than working with a local copy.  In perl you can
  123. refer to all the objects of a particular name by prefixing the name
  124. with a star: C<*foo>.  This is often known as a "type glob", since the
  125. star on the front can be thought of as a wildcard match for all the
  126. funny prefix characters on variables and subroutines and such.
  127.  
  128. When evaluated, the type glob produces a scalar value that represents
  129. all the objects of that name, including any filehandle, format or
  130. subroutine.  When assigned to, it causes the name mentioned to refer to
  131. whatever "*" value was assigned to it.  Example:
  132.  
  133.     sub doubleary {
  134.     local(*someary) = @_;
  135.     foreach $elem (@someary) {
  136.         $elem *= 2;
  137.     }
  138.     }
  139.     doubleary(*foo);
  140.     doubleary(*bar);
  141.  
  142. Note that scalars are already passed by reference, so you can modify
  143. scalar arguments without using this mechanism by referring explicitly
  144. to $_[0] etc.  You can modify all the elements of an array by passing
  145. all the elements as scalars, but you have to use the * mechanism (or
  146. the equivalent reference mechanism) to push, pop or change the size of
  147. an array.  It will certainly be faster to pass the typeglob (or reference).
  148.  
  149. Even if you don't want to modify an array, this mechanism is useful for
  150. passing multiple arrays in a single LIST, since normally the LIST
  151. mechanism will merge all the array values so that you can't extract out
  152. the individual arrays.
  153.  
  154. =head2 Overriding builtin functions
  155.  
  156. Many builtin functions may be overridden, though this should only be
  157. tried occasionally and for good reason.  Typically this might be
  158. done by a package attempting to emulate missing builtin functionality
  159. on a non-Unix system.
  160.  
  161. Overriding may only be done by importing the name from a
  162. module--ordinary predeclaration isn't good enough.  However, the
  163. C<subs> pragma (compiler directive) lets you, in effect, predeclare subs
  164. via the import syntax, and these names may then override the builtin ones:
  165.  
  166.     use subs 'chdir', 'chroot', 'chmod', 'chown';
  167.     chdir $somewhere;
  168.     sub chdir { ... }
  169.  
  170. Library modules should not in general export builtin names like "open"
  171. or "chdir" as part of their default @EXPORT list, since these may
  172. sneak into someone else's namespace and change the semantics unexpectedly.
  173. Instead, if the module adds the name to the @EXPORT_OK list, then it's
  174. possible for a user to import the name explicitly, but not implicitly.
  175. That is, they could say
  176.  
  177.     use Module 'open';
  178.  
  179. and it would import the open override, but if they said
  180.  
  181.     use Module;
  182.  
  183. they would get the default imports without the overrides.
  184.  
  185. =head2 Autoloading
  186.  
  187. If you call a subroutine that is undefined, you would ordinarily get an
  188. immediate fatal error complaining that the subroutine doesn't exist.
  189. (Likewise for subroutines being used as methods, when the method
  190. doesn't exist in any of the base classes of the class package.) If,
  191. however, there is an C<AUTOLOAD> subroutine defined in the package or
  192. packages that were searched for the original subroutine, then that
  193. C<AUTOLOAD> subroutine is called with the arguments that would have been
  194. passed to the original subroutine.  The fully qualified name of the
  195. original subroutine magically appears in the $AUTOLOAD variable in the
  196. same package as the C<AUTOLOAD> routine.  The name is not passed as an
  197. ordinary argument because, er, well, just because, that's why...
  198.  
  199. Most C<AUTOLOAD> routines will load in a definition for the subroutine in
  200. question using eval, and then execute that subroutine using a special
  201. form of "goto" that erases the stack frame of the C<AUTOLOAD> routine
  202. without a trace.  (See the standard C<AutoLoader> module, for example.)
  203. But an C<AUTOLOAD> routine can also just emulate the routine and never
  204. define it.  A good example of this is the standard Shell module, which
  205. can treat undefined subroutine calls as calls to Unix programs.
  206.  
  207. There are mechanisms available for modules to help them split themselves
  208. up into autoloadable files to be used with the standard AutoLoader module.
  209. See the document on extensions.
  210.  
  211.