home *** CD-ROM | disk | FTP | other *** search
/ BURKS 2 / BURKS_AUG97.ISO / SLAKWARE / D13 / PERL2.TGZ / perl2.tar / usr / lib / perl5 / pod / perlsub.pod < prev    next >
Text File  |  1996-06-28  |  29KB  |  792 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 parens.
  26.     NAME LIST;       # Parens 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 values are implicit
  51. references (predating L<perlref>) to the actual scalar parameters.  The
  52. return value of the subroutine is the value of the last expression
  53. evaluated.  Alternatively, a return statement may be used to specify the
  54. returned value and exit the subroutine.  If you return one or more arrays
  55. and/or hashes, these will be flattened together into one large
  56. indistinguishable list.
  57.  
  58. Perl does not have named formal parameters, but in practice all you do is
  59. assign to a my() list of these.  Any variables you use in the function
  60. that aren't declared private are global variables.  For the gory details
  61. on creating private variables, see the sections below on L<"Private
  62. Variables via my()"> and L</"Temporary Values via local()">.  To create
  63. protected environments for a set of functions in a separate package (and
  64. probably a separate file), see L<perlmod/"Packages">.
  65.  
  66. Example:
  67.  
  68.     sub max {
  69.     my $max = shift(@_);
  70.     foreach $foo (@_) {
  71.         $max = $foo if $max < $foo;
  72.     }
  73.     return $max;
  74.     }
  75.     $bestday = max($mon,$tue,$wed,$thu,$fri);
  76.  
  77. Example:
  78.  
  79.     # get a line, combining continuation lines
  80.     #  that start with whitespace
  81.  
  82.     sub get_line {
  83.     $thisline = $lookahead;  # GLOBAL VARIABLES!!
  84.     LINE: while ($lookahead = <STDIN>) {
  85.         if ($lookahead =~ /^[ \t]/) {
  86.         $thisline .= $lookahead;
  87.         }
  88.         else {
  89.         last LINE;
  90.         }
  91.     }
  92.     $thisline;
  93.     }
  94.  
  95.     $lookahead = <STDIN>;    # get first line
  96.     while ($_ = get_line()) {
  97.     ...
  98.     }
  99.  
  100. Use array assignment to a local list to name your formal arguments:
  101.  
  102.     sub maybeset {
  103.     my($key, $value) = @_;
  104.     $Foo{$key} = $value unless $Foo{$key};
  105.     }
  106.  
  107. This also has the effect of turning call-by-reference into call-by-value,
  108. since the assignment copies the values.  Otherwise a function is free to
  109. do in-place modifications of @_ and change its callers values.
  110.  
  111.     upcase_in($v1, $v2);  # this changes $v1 and $v2
  112.     sub upcase_in {
  113.     for (@_) { tr/a-z/A-Z/ } 
  114.     } 
  115.  
  116. You aren't allowed to modify constants in this way, of course.  If an
  117. argument were actually literal and you tried to change it, you'd take a
  118. (presumably fatal) exception.   For example, this won't work:
  119.  
  120.     upcase_in("frederick");
  121.  
  122. It would be much safer if the upcase_in() function 
  123. were written to return a copy of its parameters instead
  124. of changing them in place:
  125.  
  126.     ($v3, $v4) = upcase($v1, $v2);  # this doesn't
  127.     sub upcase {
  128.     my @parms = @_;
  129.     for (@parms) { tr/a-z/A-Z/ } 
  130.     # wantarray checks if we were called in list context
  131.       return wantarray ? @parms : $parms[0];
  132.     } 
  133.  
  134. Notice how this (unprototyped) function doesn't care whether it was passed
  135. real scalars or arrays.  Perl will see everything as one big long flat @_
  136. parameter list.  This is one of the ways where Perl's simple
  137. argument-passing style shines.  The upcase() function would work perfectly
  138. well without changing the upcase() definition even if we fed it things
  139. like this:
  140.  
  141.     @newlist   = upcase(@list1, @list2);
  142.     @newlist   = upcase( split /:/, $var );
  143.  
  144. Do not, however, be tempted to do this:
  145.  
  146.     (@a, @b)   = upcase(@list1, @list2);
  147.  
  148. Because like its flat incoming parameter list, the return list is also
  149. flat.  So all you have managed to do here is stored everything in @a and
  150. made @b an empty list.  See L</"Pass by Reference"> for alternatives.
  151.  
  152. A subroutine may be called using the "&" prefix.  The "&" is optional in
  153. Perl 5, and so are the parens if the subroutine has been predeclared.
  154. (Note, however, that the "&" is I<NOT> optional when you're just naming
  155. the subroutine, such as when it's used as an argument to defined() or
  156. undef().  Nor is it optional when you want to do an indirect subroutine
  157. call with a subroutine name or reference using the C<&$subref()> or
  158. C<&{$subref}()> constructs.  See L<perlref> for more on that.)
  159.  
  160. Subroutines may be called recursively.  If a subroutine is called using
  161. the "&" form, the argument list is optional, and if omitted, no @_ array is
  162. set up for the subroutine: the @_ array at the time of the call is
  163. visible to subroutine instead.  This is an efficiency mechanism that
  164. new users may wish to avoid.
  165.  
  166.     &foo(1,2,3);    # pass three arguments
  167.     foo(1,2,3);        # the same
  168.  
  169.     foo();        # pass a null list
  170.     &foo();        # the same
  171.  
  172.     &foo;        # foo() get current args, like foo(@_) !!
  173.     foo;        # like foo() IFF sub foo pre-declared, else "foo"
  174.  
  175. Not only does the "&" form make the argument list optional, but it also
  176. disables any prototype checking on the arguments you do provide.  This
  177. is partly for historical reasons, and partly for having a convenient way
  178. to cheat if you know what you're doing.  See the section on Prototypes below.
  179.  
  180. =head2 Private Variables via my()
  181.  
  182. Synopsis:
  183.  
  184.     my $foo;            # declare $foo lexically local
  185.     my (@wid, %get);     # declare list of variables local
  186.     my $foo = "flurp";    # declare $foo lexical, and init it
  187.     my @oof = @bar;    # declare @oof lexical, and init it
  188.  
  189. A "my" declares the listed variables to be confined (lexically) to the
  190. enclosing block, subroutine, C<eval>, or C<do/require/use>'d file.  If
  191. more than one value is listed, the list must be placed in parens.  All
  192. listed elements must be legal lvalues.  Only alphanumeric identifiers may
  193. be lexically scoped--magical builtins like $/ must currently be localized with
  194. "local" instead.  
  195.  
  196. Unlike dynamic variables created by the "local" statement, lexical
  197. variables declared with "my" are totally hidden from the outside world,
  198. including any called subroutines (even if it's the same subroutine called
  199. from itself or elsewhere--every call gets its own copy).
  200.  
  201. (An eval(), however, can see the lexical variables of the scope it is
  202. being evaluated in so long as the names aren't hidden by declarations within
  203. the eval() itself.  See L<perlref>.)
  204.  
  205. The parameter list to my() may be assigned to if desired, which allows you
  206. to initialize your variables.  (If no initializer is given for a
  207. particular variable, it is created with the undefined value.)  Commonly
  208. this is used to name the parameters to a subroutine.  Examples:
  209.  
  210.     $arg = "fred";      # "global" variable
  211.     $n = cube_root(27);
  212.     print "$arg thinks the root is $n\n";
  213.  fred thinks the root is 3
  214.  
  215.     sub cube_root {
  216.     my $arg = shift;  # name doesn't matter
  217.     $arg **= 1/3;
  218.     return $arg;
  219.     }             
  220.  
  221. The "my" is simply a modifier on something you might assign to.  So when
  222. you do assign to the variab