In Perl, you can create a subprogram (subroutine) by yourself ):
Keyword sub, subprogram name, and code block enclosed by curly brackets.
Sub marine {...}
The subprogram name is different from the scalar namespace.
Return Value of a subroutine: The expression of the last operation is the default return value. You can also use return to explicitly return, so that subsequent statements will not be executed.
A scalar is returned in the scalar context, and a list is returned in the list context.
Parameters in the subroutine: You can use @ _, $ _ [1], $ _ [2], and such variables to represent the parameters in the subroutine. @ _ A variable is a private variable of a subroutine. No error occurs during recursive calls.
When calling a subroutine, use the list expression enclosed in parentheses after the subroutine name.
$ N = & MAX (); # $ _ [1], 15 $ _ [2], @ _ = );
Subprogram private variable definition: The my keyword is used to declare the lexical variable (lexical variable ). My ($ M, $ n) = @ _; # create a private variable and assign a value.
It can be defined not only in subprograms, but also in if, while, and foreach.
It can only be used to declare a Single Scalar/variable, list/array. My $ Fred, $ Barney; # error. The second variable cannot be declared.
Persistent private variables: these variables are declared with the keyword state. The values before the variables are retained in multiple calls of the subroutine. The scope still exists only in the subroutine.
Sub marine {state $ n = 0; $ n + = 1; print ;}
It can also be used to declare arrays and hash types. State @ number.
Subroutine call: a subroutine can be called by (& + subroutine name.
If the compiler has seen the definition of a subroutine before, you can directly call the subroutine without adding.
If Perl can directly identify that it can only be called as a subroutine through syntax rules, it can also be omitted &.
That is, as long as youPut the parameter list in bracketsIt must be a subroutine call.
Use strict; # use strict and good programming style.
Perl's camel spirit (2)