码迷,mamicode.com
首页 > 其他好文 > 详细

perl学习之:subs函数

时间:2015-02-14 22:28:50      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

      在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函数。

perl学习之:subs函数

标签:

原文地址:http://www.cnblogs.com/chip/p/4292203.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!