📄 perlsub.1
字号:
.PP.Vb 1\& (@a, @b) = upcase(@list1, @list2);.Ve.PPLike the flattened incoming parameter list, the return list is alsoflattened on return. So all you have managed to do here is storedeverything in \f(CW@a\fR and made \f(CW@b\fR empty. See \&\*(L"Pass by Reference\*(R" for alternatives..PPA subroutine may be called using an explicit \f(CW\*(C`&\*(C'\fR prefix. The\&\f(CW\*(C`&\*(C'\fR is optional in modern Perl, as are parentheses if thesubroutine has been predeclared. The \f(CW\*(C`&\*(C'\fR is \fInot\fR optionalwhen just naming the subroutine, such as when it's used asan argument to \fIdefined()\fR or \fIundef()\fR. Nor is it optional when youwant to do an indirect subroutine call with a subroutine name orreference using the \f(CW\*(C`&$subref()\*(C'\fR or \f(CW\*(C`&{$subref}()\*(C'\fR constructs,although the \f(CW\*(C`$subref\->()\*(C'\fR notation solves that problem.See perlref for more about all that..IX Xref "&".PPSubroutines may be called recursively. If a subroutine is calledusing the \f(CW\*(C`&\*(C'\fR form, the argument list is optional, and if omitted,no \f(CW@_\fR array is set up for the subroutine: the \f(CW@_\fR array at thetime of the call is visible to subroutine instead. This is anefficiency mechanism that new users may wish to avoid..IX Xref "recursion".PP.Vb 2\& &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".Ve.PPNot only does the \f(CW\*(C`&\*(C'\fR 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 Prototypes below..IX Xref "&".PPSubroutines whose names are in all upper case are reserved to the Perlcore, as are modules whose names are in all lower case. A subroutine inall capitals is a loosely-held convention meaning it will be calledindirectly by the run-time system itself, usually due to a triggered event.Subroutines that do special, pre-defined things include \f(CW\*(C`AUTOLOAD\*(C'\fR, \f(CW\*(C`CLONE\*(C'\fR,\&\f(CW\*(C`DESTROY\*(C'\fR plus all functions mentioned in perltie and PerlIO::via..PPThe \f(CW\*(C`BEGIN\*(C'\fR, \f(CW\*(C`UNITCHECK\*(C'\fR, \f(CW\*(C`CHECK\*(C'\fR, \f(CW\*(C`INIT\*(C'\fR and \f(CW\*(C`END\*(C'\fR subroutinesare not so much subroutines as named special code blocks, of which youcan have more than one in a package, and which you can \fBnot\fR callexplicitly. See \*(L"\s-1BEGIN\s0, \s-1UNITCHECK\s0, \s-1CHECK\s0, \s-1INIT\s0 and \s-1END\s0\*(R" in perlmod.Sh "Private Variables via \fImy()\fP".IX Xref "my variable, lexical lexical lexical variable scope, lexical lexical scope attributes, my".IX Subsection "Private Variables via my()"Synopsis:.PP.Vb 5\& 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 applied.Ve.PP\&\fB\s-1WARNING\s0\fR: The use of attribute lists on \f(CW\*(C`my\*(C'\fR declarations is stillevolving. The current semantics and interface are subject to change.See attributes and Attribute::Handlers..PPThe \f(CW\*(C`my\*(C'\fR operator declares the listed variables to be lexicallyconfined to the enclosing block, conditional (\f(CW\*(C`if/unless/elsif/else\*(C'\fR),loop (\f(CW\*(C`for/foreach/while/until/continue\*(C'\fR), subroutine, \f(CW\*(C`eval\*(C'\fR,or \f(CW\*(C`do/require/use\*(C'\fR'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 \f(CW$/\fR must currently be \f(CW\*(C`local\*(C'\fRizedwith \f(CW\*(C`local\*(C'\fR instead..PPUnlike dynamic variables created by the \f(CW\*(C`local\*(C'\fR operator, lexicalvariables declared with \f(CW\*(C`my\*(C'\fR 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..IX Xref "local".PPThis doesn't mean that a \f(CW\*(C`my\*(C'\fR variable declared in a staticallyenclosing lexical scope would be invisible. Only dynamic scopesare cut off. For example, the \f(CW\*(C`bumpx()\*(C'\fR function below has accessto the lexical \f(CW$x\fR variable because both the \f(CW\*(C`my\*(C'\fR and the \f(CW\*(C`sub\*(C'\fRoccurred at the same scope, presumably file scope..PP.Vb 2\& my $x = 10;\& sub bumpx { $x++ }.Ve.PPAn \f(CW\*(C`eval()\*(C'\fR, however, can see lexical variables of the scope it isbeing evaluated in, so long as the names aren't hidden by declarations withinthe \f(CW\*(C`eval()\*(C'\fR itself. See perlref..IX Xref "eval, scope of".PPThe parameter list to \fImy()\fR 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:.PP.Vb 4\& $arg = "fred"; # "global" variable\& $n = cube_root(27);\& print "$arg thinks the root is $n\en";\& fred thinks the root is 3\&\& sub cube_root {\& my $arg = shift; # name doesn\*(Aqt matter\& $arg **= 1/3;\& return $arg;\& }.Ve.PPThe \f(CW\*(C`my\*(C'\fR is simply a modifier on something you might assign to. So whenyou do assign to variables in its argument list, \f(CW\*(C`my\*(C'\fR doesn'tchange whether those variables are viewed as a scalar or an array. So.PP.Vb 2\& my ($foo) = <STDIN>; # WRONG?\& my @FOO = <STDIN>;.Ve.PPboth supply a list context to the right-hand side, while.PP.Vb 1\& my $foo = <STDIN>;.Ve.PPsupplies a scalar context. But the following declares only one variable:.PP.Vb 1\& my $foo, $bar = 1; # WRONG.Ve.PPThat has the same effect as.PP.Vb 2\& my $foo;\& $bar = 1;.Ve.PPThe declared variable is not introduced (is not visible) until afterthe current statement. Thus,.PP.Vb 1\& my $x = $x;.Ve.PPcan be used to initialize a new \f(CW$x\fR with the value of the old \f(CW$x\fR, andthe expression.PP.Vb 1\& my $x = 123 and $x == 123.Ve.PPis false unless the old \f(CW$x\fR happened to have the value \f(CW123\fR..PPLexical 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.PP.Vb 5\& while (my $line = <>) {\& $line = lc $line;\& } continue {\& print $line;\& }.Ve.PPthe scope of \f(CW$line\fR extends from its declaration throughout the rest ofthe loop construct (including the \f(CW\*(C`continue\*(C'\fR clause), but not beyondit. Similarly, in the conditional.PP.Vb 8\& if ((my $answer = <STDIN>) =~ /^yes$/i) {\& user_agrees();\& } elsif ($answer =~ /^no$/i) {\& user_disagrees();\& } else {\& chomp $answer;\& die "\*(Aq$answer\*(Aq is neither \*(Aqyes\*(Aq nor \*(Aqno\*(Aq";\& }.Ve.PPthe scope of \f(CW$answer\fR extends from its declaration through the restof that conditional, including any \f(CW\*(C`elsif\*(C'\fR and \f(CW\*(C`else\*(C'\fR clauses, but not beyond it. See \*(L"Simple statements\*(R" in perlsyn for informationon the scope of variables in statements with modifiers..PPThe \f(CW\*(C`foreach\*(C'\fR loop defaults to scoping its index variable dynamicallyin the manner of \f(CW\*(C`local\*(C'\fR. However, if the index variable isprefixed with the keyword \f(CW\*(C`my\*(C'\fR, or if there is already a lexicalby that name in scope, then a new lexical is created instead. Thusin the loop.IX Xref "foreach for".PP.Vb 3\& for my $i (1, 2, 3) {\& some_function();\& }.Ve.PPthe scope of \f(CW$i\fR extends to the end of the loop, but not beyond it,rendering the value of \f(CW$i\fR inaccessible within \f(CW\*(C`some_function()\*(C'\fR..IX Xref "foreach for".PPSome users may wish to encourage the use of lexically scoped variables.As an aid to catching implicit uses to package variables,which are always global, if you say.PP.Vb 1\& use strict \*(Aqvars\*(Aq;.Ve.PPthen any variable mentioned from there to the end of the enclosingblock must either refer to a lexical variable, be predeclared via\&\f(CW\*(C`our\*(C'\fR or \f(CW\*(C`use vars\*(C'\fR, or else must be fully qualified with the package name.A compilation error results otherwise. An inner block may countermandthis with \f(CW\*(C`no strict \*(Aqvars\*(Aq\*(C'\fR..PPA \f(CW\*(C`my\*(C'\fR has both a compile-time and a run-time effect. At compiletime, the compiler takes notice of it. The principal usefulnessof this is to quiet \f(CW\*(C`use strict \*(Aqvars\*(Aq\*(C'\fR, but it is also essentialfor generation of closures as detailed in perlref. Actualinitialization is delayed until run time, though, so it gets executedat the appropriate time, such as each time through a loop, forexample..PPVariables declared with \f(CW\*(C`my\*(C'\fR are not part of any package and are thereforenever fully qualified with the package name. In particular, you're notallowed to try to make a package variable (or other global) lexical:.PP.Vb 1\& my $pack::var; # ERROR! Illegal syntax.Ve.PPIn fact, a dynamic variable (also known as package or global variables)are still accessible using the fully qualified \f(CW\*(C`::\*(C'\fR notation even while alexical of the same name is also visible:.PP.Vb 4\& package main;\& local $x = 10;\& my $x = 20;\& print "$x and $::x\en";.Ve.PPThat will print out \f(CW20\fR and \f(CW10\fR..PPYou may declare \f(CW\*(C`my\*(C'\fR variables at the outermost scope of a fileto hide any such identifiers from the world outside that file. Thisis similar in spirit to C's static variables when they are used atthe file level. To do this with a subroutine requires the use ofa closure (an anonymous function that accesses enclosing lexicals).If you want to create a private subroutine that cannot be calledfrom outside that block, it can declare a lexical variable containingan anonymous sub reference:.PP.Vb 3\& my $secret_version = \*(Aq1.001\-beta\*(Aq;\& my $secret_sub = sub { print $secret_version };\& &$secret_sub();.Ve.PPAs long as the reference is never returned by any function within themodule, no outside module can see the subroutine, because its name is not inany package's symbol table. Remember that it's not \fI\s-1REALLY\s0\fR called\&\f(CW$some_pack::secret_version\fR or anything; it's just \f(CW$secret_version\fR,unqualified and unqualifiable..PPThis does not work with object methods, however; all object methodshave to be in the symbol table of some package to be found. See\&\*(L"Function Templates\*(R" in perlref for something of a work-around tothis..Sh "Persistent Private Variables".IX Xref "state state variable static variable, persistent variable, static closure".IX Subsection "Persistent Private Variables"There are two ways to build persistent private variables in Perl 5.10.First, you can simply use the \f(CW\*(C`state\*(C'\fR feature. Or, you can use closures,if you want to stay compatible with releases older than 5.10..PP\fIPersistent variables via \fIstate()\fI\fR.IX Subsection "Persistent variables via state()".PPBeginning with perl 5.9.4, you can declare variables with the \f(CW\*(C`state\*(C'\fRkeyword in place of \f(CW\*(C`my\*(C'\fR. For that to work, though, you must haveenabled that feature beforehand, either by using the \f(CW\*(C`feature\*(C'\fR pragma, orby using \f(CW\*(C`\-E\*(C'\fR on one-liners. (see feature).PPFor example, the following code maintains a private counter, incrementedeach time the \fIgimme_another()\fR function is called:.PP.Vb 2\& use feature \*(Aqstate\*(Aq;\& sub gimme_another { state $x; return ++$x }.Ve.PPAlso, since \f(CW$x\fR is lexical, it can't be reached or modified by any Perlcode outside..PPWhen combined with variable declaration, simple scalar assignment to \f(CW\*(C`state\*(C'\fRvariables (as in \f(CW\*(C`state $x = 42\*(C'\fR) is executed only the first time. When suchstatements are evaluated subsequent times, the assignment is ignored. Thebehavior of this sort of assignment to non-scalar variables is undefined..PP\fIPersistent variables with closures\fR.IX Subsection "Persistent variables with closures".PPJust because a lexical variable is lexically (also called statically)scoped to its enclosing block, \f(CW\*(C`eval\*(C'\fR, or \f(CW\*(C`do\*(C'\fR \s-1FILE\s0, this doesn't mean thatwithin a function it works like a C static. It normally works morelike a C auto, but with implicit garbage collection..PPUnlike local variables in C or \*(C+, Perl's lexical variables don'tnecessarily get recycled just because their scope has exited.If something more permanent is still aware of the lexical, it willstick around. So long as something else references a lexical, thatlexical won't be freed\*(--which is as it should be. You wouldn't wantmemory being free until you were done using it, or kept around once youwere done. Automatic garbage collection takes care of this for you..PPThis means that you can pass back or save away references to lexicalvariables, whereas to return a pointer to a C auto is a grave error.It also gives us a way to simulate C's function statics. Here's amechanism for giving a function private variables with both lexicalscoping and a static lifetime. If you do want to create something likeC's static variables, just enclose the whole function in an extra block,and put the static variable outside the function but in the block..PP
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -