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 >
Wrap
Text File
|
1996-06-28
|
29KB
|
792 lines
=head1 NAME
perlsub - Perl subroutines
=head1 SYNOPSIS
To declare subroutines:
sub NAME; # A "forward" declaration.
sub NAME(PROTO); # ditto, but with prototypes
sub NAME BLOCK # A declaration and a definition.
sub NAME(PROTO) BLOCK # ditto, but with prototypes
To define an anonymous subroutine at runtime:
$subref = sub BLOCK;
To import subroutines:
use PACKAGE qw(NAME1 NAME2 NAME3);
To call subroutines:
NAME(LIST); # & is optional with parens.
NAME LIST; # Parens optional if predeclared/imported.
&NAME; # Passes current @_ to subroutine.
=head1 DESCRIPTION
Like many languages, Perl provides for user-defined subroutines. These
may be located anywhere in the main program, loaded in from other files
via the C<do>, C<require>, or C<use> keywords, or even generated on the
fly using C<eval> or anonymous subroutines (closures). You can even call
a function indirectly using a variable containing its name or a CODE reference
to it, as in C<$var = \&function>.
The Perl model for function call and return values is simple: all
functions are passed as parameters one single flat list of scalars, and
all functions likewise return to their caller one single flat list of
scalars. Any arrays or hashes in these call and return lists will
collapse, losing their identities--but you may always use
pass-by-reference instead to avoid this. Both call and return lists may
contain as many or as few scalar elements as you'd like. (Often a
function without an explicit return statement is called a subroutine, but
there's really no difference from the language's perspective.)
Any arguments passed to the routine come in as the array @_. Thus if you
called a function with two arguments, those would be stored in C<$_[0]>
and C<$_[1]>. The array @_ is a local array, but its values are implicit
references (predating L<perlref>) to the actual scalar parameters. The
return value of the subroutine is the value of the last expression
evaluated. Alternatively, a return statement may be used to specify the
returned value and exit the subroutine. If you return one or more arrays
and/or hashes, these will be flattened together into one large
indistinguishable list.
Perl does not have named formal parameters, but in practice all you do is
assign to a my() list of these. Any variables you use in the function
that aren't declared private are global variables. For the gory details
on creating private variables, see the sections below on L<"Private
Variables via my()"> and L</"Temporary Values via local()">. To create
protected environments for a set of functions in a separate package (and
probably a separate file), see L<perlmod/"Packages">.
Example:
sub max {
my $max = shift(@_);
foreach $foo (@_) {
$max = $foo if $max < $foo;
}
return $max;
}
$bestday = max($mon,$tue,$wed,$thu,$fri);
Example:
# get a line, combining continuation lines
# that start with whitespace
sub get_line {
$thisline = $lookahead; # GLOBAL VARIABLES!!
LINE: while ($lookahead = <STDIN>) {
if ($lookahead =~ /^[ \t]/) {
$thisline .= $lookahead;
}
else {
last LINE;
}
}
$thisline;
}
$lookahead = <STDIN>; # get first line
while ($_ = get_line()) {
...
}
Use array assignment to a local list to name your formal arguments:
sub maybeset {
my($key, $value) = @_;
$Foo{$key} = $value unless $Foo{$key};
}
This also has the effect of turning call-by-reference into call-by-value,
since the assignment copies the values. Otherwise a function is free to
do in-place modifications of @_ and change its callers values.
upcase_in($v1, $v2); # this changes $v1 and $v2
sub upcase_in {
for (@_) { tr/a-z/A-Z/ }
}
You aren't allowed to modify constants in this way, of course. If an
argument were actually literal and you tried to change it, you'd take a
(presumably fatal) exception. For example, this won't work:
upcase_in("frederick");
It would be much safer if the upcase_in() function
were written to return a copy of its parameters instead
of changing them in place:
($v3, $v4) = upcase($v1, $v2); # this doesn't
sub upcase {
my @parms = @_;
for (@parms) { tr/a-z/A-Z/ }
# wantarray checks if we were called in list context
return wantarray ? @parms : $parms[0];
}
Notice how this (unprototyped) function doesn't care whether it was passed
real scalars or arrays. Perl will see everything as one big long flat @_
parameter list. This is one of the ways where Perl's simple
argument-passing style shines. The upcase() function would work perfectly
well without changing the upcase() definition even if we fed it things
like this:
@newlist = upcase(@list1, @list2);
@newlist = upcase( split /:/, $var );
Do not, however, be tempted to do this:
(@a, @b) = upcase(@list1, @list2);
Because like its flat incoming parameter list, the return list is also
flat. So all you have managed to do here is stored everything in @a and
made @b an empty list. See L</"Pass by Reference"> for alternatives.
A subroutine may be called using the "&" prefix. The "&" is optional in
Perl 5, and so are the parens if the subroutine has been predeclared.
(Note, however, that the "&" is I<NOT> optional when you're just naming
the subroutine, such as when it's used as an argument to defined() or
undef(). Nor is it optional when you want to do an indirect subroutine
call with a subroutine name or reference using the C<&$subref()> or
C<&{$subref}()> constructs. See L<perlref> for more on that.)
Subroutines may be called recursively. If a subroutine is called using
the "&" form, the argument list is optional, and if omitted, no @_ array is
set up for the subroutine: the @_ array at the time of the call is
visible to subroutine instead. This is an efficiency mechanism that
new users may wish to avoid.
&foo(1,2,3); # pass three arguments
foo(1,2,3); # the same
foo(); # pass a null list
&foo(); # the same
&foo; # foo() get current args, like foo(@_) !!
foo; # like foo() IFF sub foo pre-declared, else "foo"
Not only does the "&" form make the argument list optional, but it also
disables any prototype checking on the arguments you do provide. This
is partly for historical reasons, and partly for having a convenient way
to cheat if you know what you're doing. See the section on Prototypes below.
=head2 Private Variables via my()
Synopsis:
my $foo; # declare $foo lexically local
my (@wid, %get); # declare list of variables local
my $foo = "flurp"; # declare $foo lexical, and init it
my @oof = @bar; # declare @oof lexical, and init it
A "my" declares the listed variables to be confined (lexically) to the
enclosing block, subroutine, C<eval>, or C<do/require/use>'d file. If
more than one value is listed, the list must be placed in parens. All
listed elements must be legal lvalues. Only alphanumeric identifiers may
be lexically scoped--magical builtins like $/ must currently be localized with
"local" instead.
Unlike dynamic variables created by the "local" statement, lexical
variables declared with "my" are totally hidden from the outside world,
including any called subroutines (even if it's the same subroutine called
from itself or elsewhere--every call gets its own copy).
(An eval(), however, can see the lexical variables of the scope it is
being evaluated in so long as the names aren't hidden by declarations within
the eval() itself. See L<perlref>.)
The parameter list to my() may be assigned to if desired, which allows you
to initialize your variables. (If no initializer is given for a
particular variable, it is created with the undefined value.) Commonly
this is used to name the parameters to a subroutine. Examples:
$arg = "fred"; # "global" variable
$n = cube_root(27);
print "$arg thinks the root is $n\n";
fred thinks the root is 3
sub cube_root {
my $arg = shift; # name doesn't matter
$arg **= 1/3;
return $arg;
}
The "my" is simply a modifier on something you might assign to. So when
you do assign to the variab