Definition of a function
A subroutine is a piece of detached code that allows you to reduce duplicate code and the program is readable. In Perl, subroutines can appear anywhere in the program. But usually at the beginning or end of the program.
Copy Code code as follows:
Sub subroutine{
statements;
}
Sub start, subroutine name same as variable naming rules, you can have the same name as the variable, it is best not to have the same name as the internal function, if the same name as the internal function with $subroutine distinction, do not & is internal functions, & is the definition of functions, but omit & confusion.
Subroutine definition with prototype description:
Copy Code code as follows:
Sub Subroutine ($$) {#需要两个简单变量的参数
statements;
}
Description
1. () The symbol represents the type of the parameter, which represents an argument in one character.
2.$ simple variable @ List% hash & Anonymous subroutine * reference
3. Pre-Add to force type consistency, separating required parameters and optional parameters.
4.\@$;$ indicates that the first argument is a list, the second argument is a simple variable, and the third argument is a simple variable that is optional.
Second, function return value
1. The value of the last statement executed in the default subroutine is used as the return value, if the last statement executed in the If block, although not the last sentence of the subroutine, is the return value.
Copy Code code as follows:
Not equal to, direct $retval;
Copy Code code as follows:
Split (/:/,@a) returns an array.
2. Statement return (retval) exits the subroutine and returns the value Retval,retval can be a list.
3. Return error
Return returns error undef
With the eval (' subroutine ') function, the error is obtained from the $@ variable.
Iii. Transfer of function parameters
Form:
Copy Code code as follows:
$sub 1 ($num 1, $unm 2, $num 3); Call
Sub sub1{
My ($num 1, $unm 2, $num 3) =@_;
}
My $num 1=shift;
My $num 2=shift;
My $num 3=pop;
Description
1. All parameters in array @_, each element is $_[0],$_[1]
2.@_,$_[] is a local variable, when the subroutine in the subroutine, @_ does not change, will be reborn into another @_.
3. Changing the value of elements within @_ such as $_[0] changes the parameter values of the main program.
4.shift pop takes one parameter at a time. For @_ operations, shift takes the first argument and then deletes it, and the pop takes the last parameter and deletes it.