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