To define a sub-program :
To define your own subroutine, you can use the keyword sub, the subroutine name (not including the number), and the block of code enclosed in curly braces, for example:
1 Sub marine{2 $n + =1; # global variable $n 3 Print $n \n "; 4 }
Subroutines do not need to be declared beforehand
The definition of a subroutine is global and there is no private subroutine
If you define two sub-programs with the same name, the following subroutine overwrites the
Calling a sub-program
1 &marine;
return value
The result of the last operation in the subroutine is automatically treated as the return value of the subroutine.
Parameters
To pass a list of arguments to a subroutine, simply add a list expression that is enclosed by parentheses after the subroutine call, for example:
1 $n = &max (N);
Private variables in sub-programs
By default, all of the variables in Perl are global variables, and you can use the My operator to create private variables, which we call lexical variables
1 Submax{2 my($m,$n);#The new private variable in the statement block3($m,$n) =@_;#Assigning a parameter to a variable4 If($m>$n){$m}Else{$n} 5}
the improved &max Sub-Program
1 $maxinum=$max(3,5,Ten,4,6);2 Submax{3 my($max _so_far) =Shift @_;#the first value in the array, temporarily treating it as a maximum value4 foreach(@_){#traversing other elements in the array @_5 if($_>$max _so_far){#is the current element larger than $max_so_far?6 $max _so_far=$_;7 }8 }9 $max _so_far;Ten}
Use Strict Compiling Instructions
More rigorous code and compilation style
return operator
Immediately stop executing the subroutine and return a value
Perl Learning Notes (iv)--subroutines