subroutine definition and return value
Sub sum{ print" called sub-program \ n"; $a $b # The latter behavior returns a value }$a=1; $b=; $s # 34 Calling Subroutines
Sub-program parameters, parameters fixed (The following example can only 2 parameters), the first parameter of the program is $_[0], the second is $[1], and so on
Sub Max { if($_[0$_[1]) { $_[ 0]; } Else { $_[1]; }} $n = & Max (the result is
Private variables in subroutines
Sub Max { my($m,$n@_;}
Limit parameter length
Sub max{ if(@_2) { print" waring! &max arguments not match" }}
Variable-length parameter list
SubMax {my($max _num) =Shift @_;#the first value in the array foreach(@_){ if($_>$max _num){ $max _num=$_; } } $max _num;}$maximum= &max (1,6,Ten,5, -,9);Print $maximum
About my variables
my ($num@_# List Context my$num@_# Header Context my @_;
preferably using use strict;
Use 5.012 #自动加载strict编译指令
return operator
If like in a child function, the foreach end can be terminated with the return operator.
Omit & and sign
The general situation can be omitted, if it is defined with the same name as the built-in function, such as chomp, it cannot be omitted, the call must be &chomp;
Non-header return value
Sub sum{ 1.. Ten ;}
Persistent private variable state, if you use global variables in strict mode, you will get an error.
UseStrict; Usefeature QW (state);Submarine{ State$n=0; $n+=1; Print "$n \ n";}&marine;#1&marine;#2&marine;#3
Introduction to Perl Language-4th Chapter-sub-Program