Perl Function (Subprogram) Learning Notes

Time:2019-4-28

Definition of function

A subroutine is a separate piece of code that reduces duplication and makes the program readable. In perl, subroutines can appear anywhere in the program. But they are usually placed at the beginning or end of the program.

Copy codeThe code is as follows:
sub subroutine{
    statements;
}

At the beginning of sub, the naming rules of subroutines with the same variable name can be the same as variables. It’s better not to have the same name as internal functions. If they have the same name as internal functions, they should be distinguished by $subroutine. It’s not necessary to use internal functions, but it’s confusing to define functions with omitting them.

Subprogram definitions with prototype specifications:

Copy codeThe code is as follows:
sub subroutine($$){   #需要两个简单变量的参数
    statements;
}

Explain:

1. Symbols in () denote the type of parameter and a character denotes a parameter.
2. $Simple Variable @List% Hash & Anonymous Subprogram * Reference
3. Pre-add\ for the same type of coercion; Separate the necessary and optional parameters.
4. @$; $means that the first parameter is a list, the second parameter is a simple variable, and the third parameter is optional.

Function Return Value

1. The value of the last statement executed in the default subroutine will be used as a return value. If the statement executed last in the if block is not the last sentence of the subroutine, it is also a return value.

Copy codeThe code is as follows:
$a=1;

It doesn’t need to be equal to $retval directly.

Copy codeThe code is as follows:
Split (/:/, @a) returns an array.

2. The statement return (retval) exits the subroutine and returns the value retval, which can be a list.

3. Return error

Return return return error undef

With the Eval (‘subroutine’) function, the error is obtained from the [email protected] variable.

3. Transfer of Functional Parameters

Form:

Copy codeThe code is as follows:
$sub1 ($num1, $unm2, $num3); call
sub sub1{
my($num1,$unm2,$num3)[email protected]_;
}
my $num1=shift;
my $num2=shift;
my $num3=pop;

Explain:

1. All parameters are in the array @ _and each element is $[0], $[1]
2. @, $[] is a local variable. When the subroutine is called again, another @ will be generated if @ does not change.
3. Changing the value of elements in @ such as $[0] will change the parameter value of the main program.
4. Shift pop takes one parameter at a time. For @ operation, shift takes the first parameter, then deletes it, pop takes the last parameter and then deletes it.