perlsub.pod
来自「ARM上的如果你对底层感兴趣」· POD 代码 · 共 1,150 行 · 第 1/3 页
POD
1,150 行
=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; # no proto
$subref = sub (PROTO) BLOCK; # with proto
To import subroutines:
use PACKAGE qw(NAME1 NAME2 NAME3);
To call subroutines:
NAME(LIST); # & is optional with parentheses.
NAME LIST; # Parentheses optional if predeclared/imported.
&NAME; # Makes current @_ visible to called 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.
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 C<@_>. Thus if you
called a function with two arguments, those would be stored in C<$_[0]>
and C<$_[1]>. The array C<@_> is a local array, but its elements are
aliases for the actual scalar parameters. In particular, if an element
C<$_[0]> is updated, the corresponding argument is updated (or an error
occurs if it is not updatable). If an argument is an array or hash
element which did not exist when the function was called, that element is
created only when (and if) it is modified or if a reference to it is
taken. (Some earlier versions of Perl created the element whether or not
it was assigned to.) Note that assigning to the whole array C<@_> removes
the aliasing, and does not update any arguments.
The return value of the subroutine is the value of the last expression
evaluated. Alternatively, a C<return> statement may be used to exit the
subroutine, optionally specifying the returned value, which will be
evaluated in the appropriate context (list, scalar, or void) depending
on the context of the subroutine call. If you specify no return value,
the subroutine will return an empty list in a list context, an undefined
value in a scalar context, or nothing in a void context. 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 C<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
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 (defined($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,
because the assignment copies the values. Otherwise a function is free to
do in-place modifications of C<@_> and change its caller's 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 C<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 {
return unless defined wantarray; # void context, do nothing
my @parms = @_;
for (@parms) { tr/a-z/A-Z/ }
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 C<@_>
parameter list. This is one of the ways where Perl's simple
argument-passing style shines. The C<upcase()> function would work perfectly
well without changing the C<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 C<@a> and
made C<@b> an empty list. See L<Pass by Reference> for alternatives.
A subroutine may be called using the "C<&>" prefix. The "C<&>" is optional
in modern Perls, and so are the parentheses if the subroutine has been
predeclared. (Note, however, that the "C<&>" is I<NOT> optional when
you're just naming the subroutine, such as when it's used as an
argument to C<defined()> or C<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 "C<&>" form, the argument list is optional, and if omitted, no C<@_> array is
set up for the subroutine: the C<@_> 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 predeclared, else "foo"
Not only does the "C<&>" 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.
Function whose names are in all upper case are reserved to the Perl core,
just as are modules whose names are in all lower case. A function in
all capitals is a loosely-held convention meaning it will be called
indirectly by the run-time system itself. Functions that do special,
pre-defined things are C<BEGIN>, C<END>, C<AUTOLOAD>, and C<DESTROY>--plus all the
functions mentioned in L<perltie>. The 5.005 release adds C<INIT>
to this list.
=head2 Private Variables via C<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 "C<my>" declares the listed variables to be confined (lexically) to the
enclosing block, conditional (C<if/unless/elsif/else>), loop
(C<for/foreach/while/until/continue>), subroutine, C<eval>, or
C<do/require/use>'d file. If more than one value is listed, the list
must be placed in parentheses. All listed elements must be legal lvalues.
Only alphanumeric identifiers may be lexically scoped--magical
builtins like C<$/> must currently be C<local>ize with "C<local>" instead.
Unlike dynamic variables created by the "C<local>" operator, lexical
variables declared with "C<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).
This doesn't mean that a C<my()> variable declared in a statically
I<enclosing> lexical scope would be invisible. Only the dynamic scopes
are cut off. For example, the C<bumpx()> function below has access to the
lexical C<$x> variable because both the my and the sub occurred at the same
scope, presumably the file scope.
my $x = 10;
sub bumpx { $x++ }
(An C<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 C<eval()> itself. See L<perlref>.)
The parameter list to C<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 "C<my>" is simply a modifier on something you might assign to. So when
you do assign to the variables in its argument list, the "C<my>" doesn't
change whether those variables are viewed as a scalar or an array. So
my ($foo) = <STDIN>; # WRONG?
my @FOO = <STDIN>;
both supply a list context to the right-hand side, while
my $foo = <STDIN>;
supplies a scalar context. But the following declares only one variable:
my $foo, $bar = 1; # WRONG
That has the same effect as
my $foo;
$bar = 1;
The declared variable is not introduced (is not visible) until after
the current statement. Thus,
my $x = $x;
can be used to initialize the new $x with the value of the old C<$x>, and
the expression
my $x = 123 and $x == 123
is false unless the old C<$x> happened to have the value C<123>.
Lexical scopes of control structures are not bounded precisely by the
braces that delimit their controlled blocks; control expressions are
part of the scope, too. Thus in the loop
while (defined(my $line = <>)) {
$line = lc $line;
} continue {
print $line;
}
the scope of C<$line> extends from its declaration throughout the rest of
the loop construct (including the C<continue> clause), but not beyond
it. Similarly, in the conditional
if ((my $answer = <STDIN>) =~ /^yes$/i) {
user_agrees();
} elsif ($answer =~ /^no$/i) {
user_disagrees();
} else {
chomp $answer;
die "'$answer' is neither 'yes' nor 'no'";
}
the scope of C<$answer> extends from its declaration throughout the rest
of the conditional (including C<elsif> and C<else> clauses, if any),
but not beyond it.
(None of the foregoing applies to C<if/unless> or C<while/until>
modifiers appended to simple statements. Such modifiers are not
control structures and have no effect on scoping.)
The C<foreach> loop defaults to scoping its index variable dynamically
(in the manner of C<local>; see below). However, if the index
variable is prefixed with the keyword "C<my>", then it is lexically
scoped instead. Thus in the loop
for my $i (1, 2, 3) {
some_function();
}
the scope of C<$i> extends to the end of the loop, but not beyond it, and
so the value of C<$i> is unavailable in C<some_function()>.
Some users may wish to encourage the use of lexically scoped variables.
As an aid to catching implicit references to package variables,
if you say
use strict 'vars';
then any variable reference from there to the end of the enclosing
block must either refer to a lexical variable, or must be fully
qualified with the package name. A compilation error results
otherwise. An inner block may countermand this with S<"C<no strict 'vars'>">.
A C<my()> has both a compile-time and a run-time effect. At compile time,
the compiler takes notice of it; the principle usefulness of this is to
quiet S<"C<use strict 'vars'>">. The actual initialization is delayed until
run time, so it gets executed appropriately; every time through a loop,
for example.
Variables declared with "C<my>" are not part of any package and are therefore
never fully qualified with the package name. In particular, you're not
allowed to try to make a package variable (or other global) lexical:
my $pack::var; # ERROR! Illegal syntax
my $_; # also illegal (currently)
In fact, a dynamic variable (also known as package or global variables)
are still accessible using the fully qualified C<::> notation even while a
lexical of the same name is also visible:
package main;
local $x = 10;
my $x = 20;
print "$x and $::x\n";
That will print out C<20> and C<10>.
You may declare "C<my>" variables at the outermost scope of a file to hide
any such identifiers totally from the outside world. This is similar
to C's static variables at the file level. To do this with a subroutine
requires the use of a closure (anonymous function with lexical access).
If a block (such as an C<eval()>, function, or C<package>) wants to create
a private subroutine that cannot be called from outside that block,
it can declare a lexical variable containing an anonymous sub reference:
my $secret_version = '1.001-beta';
my $secret_sub = sub { print $secret_version };
&$secret_sub();
As long as the reference is never returned by any function within the
module, no outside module can see the subroutine, because its name is not in
any package's symbol table. Remember that it's not I<REALLY> called
C<$some_pack::secret_version> or anything; it's just C<$secret_version>,
unqualified and unqualifiable.
This does not work with object methods, however; all object methods have
to be in the symbol table of some package to be found.
=head2 Peristent Private Variables
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?