子程序
1、定义子程序:
关键字:sub、子程序名、代码块
=============================
sub marine {
?? $n+=1;
?? print "hello,sailor number $n!n";
}
=============================
2、调用子程序:
&marine;? #hello,sailor number 1!
3、返回值
??? 在perl中,所有的子程序都有一个返回值---子程序并没有“返回值”和“没有返回值”之分
。但并不是所有的perl子程序都包含有用的返回值。
??? 在子程序的执行过程中,它会不断进行运算。而最后一次运算的结果,都会被自动当作子程
序的返回值。
=============================
sub marine {
?? $n+=1;
?? print "hello,sailor number $n!n";
?? 1+2;
}
my $ii =&marine;
print $ii;
结果:
E:perl>perl p.pl
hello,sailor number 1!
3
=============================
??? return操作符:立即返回某个值,不要执行子程序的其余部分。
4、参数
perl会自动将参数列表化名为特殊的数组变量@_
5、私有变量和持久性私有变量
? 1)默认,变量都是全局变量;要定义私有变量:使用关键字my.
? 2)state 来声明变量,则在子程序的多次调用间保留该变量的值。
==============================
sub marine {
?? my $n+=1;?? ---声明为私有变量
?? print "hello,sailor number $n!n";
}
&marine;?
&marine;
输出:
E:perl>perl p.pl
hello,sailor number 1!?? ----两次的结果都为1;
hello,sailor number 1!
程序2:
use feature qw(state);
sub marine {
?? state $n = 0;
?? $n+=1;
?? print "hello,sailor number $n!n";
}
&marine;
&marine;
结果:
E:perl>perl p.pl
hello,sailor number 1! ----两次的结果递增;
hello,sailor number 2!
注意:
要加入use feature qw(state);或者use 5.010;
这是因为:
state这个是在perl 5.0.10里面提供的功能,
需要明确指明,才可以使用。在perldoc里有这么一段:"state" variables are only enabled
when the "feature 'state'" pragma is in effect。
但是不能在列表上下文中初始化数组和哈希类的state变量。
==============================
注意:
1)perl允许省略语句块中最后一个分号。
2)除非调用子程序的时候前面加了“与号”,且后面没有括号,那种特殊情况下@_数组会从调用
者上下文中继承下来,一般来说这不是个好主意,但有时也有它的用处。
3)省略“与号”:编译器在调用子程序之前看到了子程序的定义,或者perl可以从语法识别它是
子程序调用,那么该子程序可以像内置函数那样,在调用时省略“与号”。