通常将可重复使用的代码组织起来形成函数。 Perl 用关键字 sub 声明函数,紧接着用 { 号开始 } 结束:
Functions are used to organize your code into small pieces which can be reused. Perl declares functions using the sub keyword followed by the { sign to start the function and the } to end it:
sub function1 {
CODE HERE
}
调用 Perl 函数的方式:用 & 符号后紧随着函数名称。如果函数中包含有参数,应该将用圆括号将参数包含:
In order to call a Perl function it's suggested that you call it using the & sign followed by the function name. If you have parameters, they can be also passed, so it's suggested that you enclose them in parentheses:
&function1;
在 Perl 中 , 函数作为过程被调用时不返回值 , 当然函数调用后也可以返回一个值(具体怎样操作,稍后将会讲述)。上面的示例代码所调用函数相当于一个过程,而下面的这个示例表示函数被调用后返回一个值(我们同样需要传参数值给函数)。
In Perl, functions can serve as procedures which do not return a value (in reality they do, but that will be discussed later), or functions which do return a value. The above example is of a function that acts as a procedure. Below is an example of a function that acts as a function, because it returns a value (we are also passing values to the function):
$answer = &add(1,2);
传递给函数的参数值不必局限于标量,你也可以传递数组: @_
You aren't limited to passing only scalar values to a function. You can also pass it arrays , but it will be easier to pass them at the end.
Perl functions receive their values in an array : @_
数组将其所存储的值全部传给函数,在上面的示例中,我们传递了两个值(数组形式),我们用下面的方式在函数中接收:
This array holds all the values of the parameters passed to the function. So in the above example, where we had 2 values passed, we would retrieve them in the following manner:
sub function1 {
($val1, $val2) = @_;
}
或者也可以这么做:
or we could do it in this manner:
sub function1 {
$val1=$_[0];
$val2=$_[1];
}
参数按值传递,意味着你正在使用的是原始参数的拷贝而不是原始参数本身。如果你想用引用的方式传递,必须直接使用变量的方式( $_[subscript] )。
Perl 的变量范围与其它语言不同,在程序的开始不必声明变量,或者在函数中亦如此:你只要使用这些变量就可以了。变量的范围始终是全局的,如果你在一个函数使用一个变量,这个变量是全局的,它可以应用于其余的程序中。如果你想让这个变量仅在函数中可见,你必须声明它为一个局部变量(注:用关键字 local 指示一个局部变量):
The parameters are being passed by value, meaning that you will be working with copies of the original parameters and not the actual parameters themselves. If you wish to pass them by reference, then you would have to work directly with the variable ($_[subscript]).
Perl's scope of variables is different than most other languages. You don't have to declare your variables at the beginning of the program, or in the functions: you just use them. The scope of the variables is always global. If you use a variable in a function, it is global to the rest of the program. If you want the variable to be seen only by code within that particular function (and any other functions it may call), then you must declare it as a local variable:
sub function1 {
local($myvar)
}
上面的代码声明 $myvar 为局部变量,因此,它不能被其余程序所使用。
The above code will declare $myvar as local, so it can't be seen by the rest of the program.
函数同样可以相互嵌套调用自身,例如,递归函数。
Functions can also be nested within each other, and you can create recursive functions that call themselves.