perlsub.pod

来自「MSYS在windows下模拟了一个类unix的终端」· POD 代码 · 共 1,279 行 · 第 1/4 页

POD
1,279
字号
=head1 NAMEperlsub - Perl subroutines=head1 SYNOPSISTo declare subroutines:    sub NAME;			  # A "forward" declaration.    sub NAME(PROTO);		  #  ditto, but with prototypes    sub NAME : ATTRS;		  #  with attributes    sub NAME(PROTO) : ATTRS;	  #  with attributes and prototypes    sub NAME BLOCK		  # A declaration and a definition.    sub NAME(PROTO) BLOCK	  #  ditto, but with prototypes    sub NAME : ATTRS BLOCK	  #  with attributes    sub NAME(PROTO) : ATTRS BLOCK #  with prototypes and attributesTo define an anonymous subroutine at runtime:    $subref = sub BLOCK;		 # no proto    $subref = sub (PROTO) BLOCK;	 # with proto    $subref = sub : ATTRS BLOCK;	 # with attributes    $subref = sub (PROTO) : ATTRS BLOCK; # with proto and attributesTo import subroutines:    use MODULE qw(NAME1 NAME2 NAME3);To call subroutines:    NAME(LIST);	   # & is optional with parentheses.    NAME LIST;	   # Parentheses optional if predeclared/imported.    &NAME(LIST);   # Circumvent prototypes.    &NAME;	   # Makes current @_ visible to called subroutine.=head1 DESCRIPTIONLike many languages, Perl provides for user-defined subroutines.These may be located anywhere in the main program, loaded in fromother files via the C<do>, C<require>, or C<use> keywords, orgenerated on the fly using C<eval> or anonymous subroutines.You can even call a function indirectly using a variable containingits name or a CODE reference.The Perl model for function call and return values is simple: allfunctions are passed as parameters one single flat list of scalars, andall functions likewise return to their caller one single flat list ofscalars.  Any arrays or hashes in these call and return lists willcollapse, losing their identities--but you may always usepass-by-reference instead to avoid this.  Both call and return lists maycontain as many or as few scalar elements as you'd like.  (Often afunction without an explicit return statement is called a subroutine, butthere's really no difference from Perl's perspective.)Any arguments passed in show up in the array C<@_>.  Therefore, ifyou called a function with two arguments, those would be stored inC<$_[0]> and C<$_[1]>.  The array C<@_> is a local array, but itselements are aliases for the actual scalar parameters.  In particular,if an element C<$_[0]> is updated, the corresponding argument isupdated (or an error occurs if it is not updatable).  If an argumentis an array or hash element which did not exist when the functionwas called, that element is created only when (and if) it is modifiedor a reference to it is taken.  (Some earlier versions of Perlcreated the element whether or not the element was assigned to.)Assigning to the whole array C<@_> removes that aliasing, and doesnot update any arguments.The return value of a subroutine is the value of the last expressionevaluated.  More explicitly, a C<return> statement may be used to exit thesubroutine, optionally specifying the returned value, which will beevaluated in the appropriate context (list, scalar, or void) dependingon the context of the subroutine call.  If you specify no return value,the subroutine returns an empty list in list context, the undefinedvalue in scalar context, or nothing in void context.  If you returnone or more aggregates (arrays and hashes), these will be flattenedtogether into one large indistinguishable list.Perl does not have named formal parameters.  In practice all youdo is assign to a C<my()> list of these.  Variables that aren'tdeclared to be private are global variables.  For gory detailson creating private variables, see L<"Private Variables via my()">and L<"Temporary Values via local()">.  To create protectedenvironments for a set of functions in a separate package (andprobably 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;	    }	}	return $thisline;    }    $lookahead = <STDIN>;	# get first line    while (defined($line = get_line())) {	...    }Assigning to a list of private variables to name your arguments:    sub maybeset {	my($key, $value) = @_;	$Foo{$key} = $value unless $Foo{$key};    }Because the assignment copies the values, this also has the effectof turning call-by-reference into call-by-value.  Otherwise afunction is free to do in-place modifications of C<@_> and changeits 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 anargument 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()> functionwere written to return a copy of its parameters insteadof changing them in place:    ($v3, $v4) = upcase($v1, $v2);  # this doesn't change $v1 and $v2    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 waspassed real scalars or arrays.  Perl sees all arguments as one big,long, flat parameter list in C<@_>.  This is one area wherePerl'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);Like the flattened incoming parameter list, the return list is alsoflattened on return.  So all you have managed to do here is storedeverything in C<@a> and made C<@b> an empty list.  See L<Pass by Reference> for alternatives.A subroutine may be called using an explicit C<&> prefix.  TheC<&> is optional in modern Perl, as are parentheses if thesubroutine has been predeclared.  The C<&> is I<not> optionalwhen just naming the subroutine, such as when it's used asan argument to defined() or undef().  Nor is it optional when youwant to do an indirect subroutine call with a subroutine name orreference using the C<&$subref()> or C<&{$subref}()> constructs,although the C<< $subref->() >> notation solves that problem.See L<perlref> for more about all that.Subroutines may be called recursively.  If a subroutine is calledusing the C<&> form, the argument list is optional, and if omitted,no C<@_> array is set up for the subroutine: the C<@_> array at thetime of the call is visible to subroutine instead.  This is anefficiency 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, it alsodisables any prototype checking on arguments you do provide.  Thisis partly for historical reasons, and partly for having a convenient wayto cheat if you know what you're doing.  See L<Prototypes> below.Functions whose names are in all upper case are reserved to the Perlcore, as are modules whose names are in all lower case.  Afunction in all capitals is a loosely-held convention meaning itwill be called indirectly by the run-time system itself, usuallydue to a triggered event.  Functions that do special, pre-definedthings include C<BEGIN>, C<CHECK>, C<INIT>, C<END>, C<AUTOLOAD>, andC<DESTROY>--plus all functions mentioned in L<perltie>.=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    my $x : Foo = $y;	# similar, with an attribute appliedB<WARNING>: The use of attribute lists on C<my> declarations isexperimental.  This feature should not be relied upon.  It maychange or disappear in future releases of Perl.  See L<attributes>.The C<my> operator declares the listed variables to be lexicallyconfined 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, thelist must be placed in parentheses.  All listed elements must belegal lvalues.  Only alphanumeric identifiers may be lexicallyscoped--magical built-ins like C<$/> must currently be C<local>izewith C<local> instead.Unlike dynamic variables created by the C<local> operator, lexicalvariables declared with C<my> are totally hidden from the outsideworld, including any called subroutines.  This is true if it's thesame subroutine called from itself or elsewhere--every call getsits own copy.This doesn't mean that a C<my> variable declared in a staticallyenclosing lexical scope would be invisible.  Only dynamic scopesare cut off.   For example, the C<bumpx()> function below has accessto the lexical $x variable because both the C<my> and the C<sub>occurred at the same scope, presumably file scope.    my $x = 10;    sub bumpx { $x++ } An C<eval()>, however, can see lexical variables of the scope it isbeing evaluated in, so long as the names aren't hidden by declarations withinthe C<eval()> itself.  See L<perlref>.The parameter list to my() may be assigned to if desired, which allows youto initialize your variables.  (If no initializer is given for aparticular variable, it is created with the undefined value.)  Commonlythis is used to name input 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 whenyou do assign to variables in its argument list, C<my> doesn'tchange 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;			# WRONGThat has the same effect as    my $foo;    $bar = 1;The declared variable is not introduced (is not visible) until afterthe current statement.  Thus,    my $x = $x;can be used to initialize a new $x with the value of the old $x, andthe expression    my $x = 123 and $x == 123is false unless the old $x happened to have the value C<123>.Lexical scopes of control structures are not bounded precisely by thebraces that delimit their controlled blocks; control expressions arepart of that scope, too.  Thus in the loop    while (my $line = <>) {        $line = lc $line;    } continue {        print $line;    }the scope of $line extends from its declaration throughout the rest ofthe loop construct (including the C<continue> clause), but not beyondit.  Similarly, in the conditional    if ((my $answer = <STDIN>) =~ /^yes$/i) {        user_agrees();    } elsif ($answer =~ /^no$/i) {        user_disagrees();

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?