perl学习之:subs函数

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

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

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

示例脚本1: 

复制代码
use strict;
use subs qw(func1 func2);

func1;
func2;

sub func1{
    print "this is func1 ";
}

sub func2{
    print "this is func2 ";
}
 
Output:
this is func1
this is func2 
复制代码

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

示例脚本2

复制代码

use strict;
use subs qw(substr);

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

substr($str,7,2);

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

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

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

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