subs函数

      在Perl中,sub关键字主要是为了定义一个子例程,那么subs又是什么呢?

      首先subs是一个函数,用于预先声明子例程,函数的参数是预声明的函数名列表。那么这个函数存在的意义是什么?首先,通过该函数预声明的那些函数,可以在不用&或者括号的情况下使用;其次,可以覆盖内建的Perl函数,诸如substr等。 

      下面就给出俩个例子来说明下:

示例脚本1: 

use strict;
use subs qw(func1 func2);

func1;
func2;

sub func1{
    
print "this is func1\n";
}

sub func2{
    
print "this is func2\n";
}
 
Output
:
this is func1
this is func2 

   上述脚本中,调用函数func1与func2都未使用&或者括号。如果去掉开头部分的subs函数,那么上述脚本会在编译时报错。   

 

示例脚本2


use strict;
use subs qw(substr);

my $str = "String to be tested!\n";

substr($str,7,2);

print "After called substr,the \$str is $str\n";

sub substr{
    
print "I have override the built-in subroutine substr(str,index,length)\n";
}

Output
:
I have override the built
-in subroutine substr(str,index,length)
After called 
substr,the $str is String to be tested! 

    通过结合subs函数覆盖了Perl内建的subs函数。

作者:royen
出处:http://www.cnblogs.com/royenBoy 
本文采用知识共享署名-非商业性使用-相同方式共享 2.5 中国大陆许可协议进行许可,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。

  

posted @ 2010-12-16 19:54  royen  阅读(4074)  评论(0)    收藏  举报