Perl函数也叫子程序,用sub关键字定义,没有显示的参数列表,用‘@_’可以获取实参列表,用return返回value。具体用法在后面的demo中体现。
关于变量作用域
Perl中的变量默认是全局的,如果需要限制变量的作用域,比如定义子程序的私有变量,就用关键字my做声明。
local关键字可以为全局变量做临时声明,对其修改访问都只针对临时对象,退出作用域后,全局变量的value不变。这里其实我们可能会认为用my定义局部对象和用local声明全局变量的临时对象差不多,确实两者呈现的效果很类似,但是实际上在作用域上还是有些不同:例如,存在全局对象A,在子程序sub1用my定义了局部对象A,sub1随后调用了子程序sub2,那么sub2中访问A将是访问的全局对象,如果sub1中的A是用local做声明,那么在sub2中访问A访问的还是sub1中的临时对象,在CASE4中做了演示。
state关键字可以为局部对象做持久化,也就是退出作用域后,该对象不被销毁,在CASE5有演示。
#!/usr/bin/perl -w
#CASE1:compute the average oh the all params
print "\n=====CASE1=====\n";
sub getAverage{
my $paramNum = scalar(@_);
print "the number of params: $paramNum\n";
$paramSum = 0;
foreach $param (@_){
$paramSum += $param;
}
$average = $paramSum / $paramNum;
return $average;
}
@array = (10, 20 ,30, 40);
$ave = getAverage(@array);
print "average value of array(@array): $ave\n";
#CASE2:delivery list params
print "\n=====CASE2=====\n";
sub printParams{
my @list = @_;
print "print all params: @list\n";
}
$aInt = 10;
@bArray = (20,30,40);
printParams($aInt, @bArray);
#CASE3: delivery hash param
print "\n=====CASE3=====\n";
sub printHash{
my (%hash) = @_;
foreach my $key (keys %hash){
my $value = $hash{$key};
print "$key : $value\n";
}
}
%hash = ('name' => 'hunk', 'age' => 25);
printHash(%hash);
#CASE4: test local and global var
print "\n=====CASE4=====\n";
$helloString = "hello wolrld";
sub printHello{
local $helloString = "hello hunk";
print "local: $helloString\n";
printHelloSub();
}
sub printHelloSub{
print "sub: $helloString\n";
}
print "global: $helloString\n";
printHello();
print "global: $helloString\n";
#CASE5: state
print "\n=====CASE5=====\n";
use feature 'state';
sub printCount{
state $count = 0;
print "count: $count\n";
$count++;
}
for(1..3){
printCount();
}
Output:
root@n209-h246:/home/hunk/code/Project_Code_Exercise/perl/basic# ./function.pl
=====CASE1=====
the number of params: 4
average value of array(10 20 30 40): 25
=====CASE2=====
print all params: 10 20 30 40
=====CASE3=====
name : hunk
age : 25
=====CASE4=====
global: hello wolrld
local: hello hunk
sub: hello hunk
global: hello wolrld
=====CASE5=====
count: 0
count: 1
count: 2
CASE4修改local为my:
#CASE4: test local and global var
print "\n=====CASE4=====\n";
$helloString = "hello wolrld";
sub printHello{
my $helloString = "hello hunk";
print "local: $helloString\n";
printHelloSub();
}
sub printHelloSub{
print "sub: $helloString\n";
}
print "global: $helloString\n";
printHello();
print "global: $helloString\n";
=====CASE4=====
global: hello wolrld
local: hello hunk
sub: hello wolrld
global: hello wolrld