1. Sub-Program
Define subroutines: The keyword sub, the subroutine name (not included with the number), and the block of code enclosed with curly braces, which is the main body of the program;
Sub marine{
$n +=1;
Print "Hello,sailor number$n!\n";
}
The definition of a subroutine is global.
2. Calling subroutines
The subroutine name (preceded by a number) can be used in any expression to invoke it;
&marine;
3. Return value
In Perl, all subroutines have a return value-the subroutine does not have a "return value" or "no return value", but not all Perl programs contain useful return values;
For example, we define the following subroutine, and the last one is the addition expression:
Sub sum_of_fred_and_barney{
Print "Hey, you called the Sum_of_fred_and Barney subroutine!\n";
$fred + $barney; #这就是返回值
}
$fred = 3;
$barney = 4;
$wilma =&sum_of_fred_and_barney;
4. Parameters
Perl subroutines can have parameters. To pass the argument list into the subroutine, simply add the list expression after the subroutine call with the parentheses around it.
$n =&max (10,15); #包含两个参数的子程序调用
Perl automatically aliases the parameter list as a special array variable @_, which means that the first parameter of the subroutine is stored in $_[0], and the second parameter is stored in $_[1]
Sub max{
if ($_[0]>$_[1]) {
$_[0];
}
else{
$_[1];
}
}
Perl Learning Record