一、定义
子程序即执行一个特殊任务的一段分离的代码,它可以使减少重复代码且使程序易读。PERL中,子程序可以出现在程序的任何地方。定义方法为:
sub subroutine{
statements;
}
二 调用
调用方法如下:
1、用&调用
&subname;
…
sub subname{
…
}
2、先定义后调用 ,可以省略&符号
sub subname{
…
}
…
subname;
3、前向引用 ,先定义子程序名,后面再定义子程序体
sub subname;
…
subname;
…
sub subname{
…
}
4、用do调用
do my_sub(1, 2, 3);等价于&my_sub(1, 2, 3);
例如,
1 先定义后调用
|
|
sub test
|
{
|
print "hello perl\n";
|
}
|
test();
|
|
2 利用&调用 (后定义)
|
&test();
|
sub test
|
{
|
print "hello perl\n";
|
}
|
|
3 do方法调用
|
do test();
|
sub test
|
{
|
print "hello perl\n";
|
}
|
|
4 c语言声明
|
sub test;
|
test();
|
sub test
|
{
|
print "hello perl\n";
|
}
|
|