This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
This is patch.2b1f to perl5.002beta1.
[perl5.git] / pod / perlsub.pod
CommitLineData
a0d0e21e
LW
1=head1 NAME
2
3perlsub - Perl subroutines
4
5=head1 SYNOPSIS
6
7To declare subroutines:
8
9 sub NAME; # A "forward" declaration.
10 sub NAME BLOCK # A declaration and a definition.
11
748a9306
LW
12To define an anonymous subroutine at runtime:
13
14 $subref = sub BLOCK;
15
a0d0e21e
LW
16To import subroutines:
17
18 use PACKAGE qw(NAME1 NAME2 NAME3);
19
20To 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
29Any arguments passed to the routine come in as array @_, that is
30($_[0], $_[1], ...). The array @_ is a local array, but its values are
31references to the actual scalar parameters. The return value of the
32subroutine is the value of the last expression evaluated, and can be
748a9306 33either an array value or a scalar value. Alternatively, a return
a0d0e21e
LW
34statement may be used to specify the returned value and exit the
35subroutine. To create local variables see the local() and my()
36operators.
37
748a9306 38A subroutine may be called using the "&" prefix. The "&" is optional in Perl
a0d0e21e
LW
395, 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
41subroutine, such as when it's used as an argument to defined() or
42undef(). Nor is it optional when you want to do an indirect subroutine
43call with a subroutine name or reference using the C<&$subref()> or
44C<&{$subref}()> constructs. See L<perlref> for more on that.)
45
46Example:
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
59Example:
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
82Use 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
89This also has the effect of turning call-by-reference into
90call-by-value, since the assignment copies the values.
91
92Subroutines may be called recursively. If a subroutine is called using
93the "&" form, the argument list is optional. If omitted, no @_ array is
94set up for the subroutine; the @_ array at the time of the call is
95visible 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
748a9306
LW
104If a module wants to create a private subroutine that cannot be called
105from outside the module, it can declare a lexical variable containing
106an anonymous sub reference:
107
108 my $subref = sub { ... }
109 &$subref(1,2,3);
110
111As long as the reference is never returned by any function within the module,
112no outside module can see the subroutine, since its name is not in any
113package's symbol table.
114
a0d0e21e
LW
115=head2 Passing Symbol Table Entries
116
117[Note: The mechanism described in this section works fine in Perl 5, but
118the new reference mechanism is generally easier to work with. See L<perlref>.]
119
120Sometimes you don't want to pass the value of an array to a subroutine
121but rather the name of it, so that the subroutine can modify the global
122copy of it rather than working with a local copy. In perl you can
123refer to all the objects of a particular name by prefixing the name
124with a star: C<*foo>. This is often known as a "type glob", since the
125star on the front can be thought of as a wildcard match for all the
126funny prefix characters on variables and subroutines and such.
127
128When evaluated, the type glob produces a scalar value that represents
129all the objects of that name, including any filehandle, format or
130subroutine. When assigned to, it causes the name mentioned to refer to
131whatever "*" 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
142Note that scalars are already passed by reference, so you can modify
143scalar arguments without using this mechanism by referring explicitly
144to $_[0] etc. You can modify all the elements of an array by passing
145all the elements as scalars, but you have to use the * mechanism (or
146the equivalent reference mechanism) to push, pop or change the size of
147an array. It will certainly be faster to pass the typeglob (or reference).
148
149Even if you don't want to modify an array, this mechanism is useful for
150passing multiple arrays in a single LIST, since normally the LIST
151mechanism will merge all the array values so that you can't extract out
152the individual arrays.
153
154=head2 Overriding builtin functions
155
156Many builtin functions may be overridden, though this should only be
157tried occasionally and for good reason. Typically this might be
158done by a package attempting to emulate missing builtin functionality
159on a non-Unix system.
160
161Overriding may only be done by importing the name from a
162module--ordinary predeclaration isn't good enough. However, the
163C<subs> pragma (compiler directive) lets you, in effect, predeclare subs
164via 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
170Library modules should not in general export builtin names like "open"
171or "chdir" as part of their default @EXPORT list, since these may
172sneak into someone else's namespace and change the semantics unexpectedly.
173Instead, if the module adds the name to the @EXPORT_OK list, then it's
174possible for a user to import the name explicitly, but not implicitly.
175That is, they could say
176
177 use Module 'open';
178
179and it would import the open override, but if they said
180
181 use Module;
182
183they would get the default imports without the overrides.
184
185=head2 Autoloading
186
187If you call a subroutine that is undefined, you would ordinarily get an
188immediate fatal error complaining that the subroutine doesn't exist.
189(Likewise for subroutines being used as methods, when the method
190doesn't exist in any of the base classes of the class package.) If,
191however, there is an C<AUTOLOAD> subroutine defined in the package or
192packages that were searched for the original subroutine, then that
193C<AUTOLOAD> subroutine is called with the arguments that would have been
194passed to the original subroutine. The fully qualified name of the
195original subroutine magically appears in the $AUTOLOAD variable in the
196same package as the C<AUTOLOAD> routine. The name is not passed as an
197ordinary argument because, er, well, just because, that's why...
198
199Most C<AUTOLOAD> routines will load in a definition for the subroutine in
200question using eval, and then execute that subroutine using a special
201form of "goto" that erases the stack frame of the C<AUTOLOAD> routine
202without a trace. (See the standard C<AutoLoader> module, for example.)
203But an C<AUTOLOAD> routine can also just emulate the routine and never
204define it. A good example of this is the standard Shell module, which
205can treat undefined subroutine calls as calls to Unix programs.
206
207There are mechanisms available for modules to help them split themselves
208up into autoloadable files to be used with the standard AutoLoader module.
209See the document on extensions.
210