perl文件包含(do,require,use)指令介绍

2019-10-01 14:03:41于海丽

    return 0;
}
1;
__END__

3. use
参看http://perldoc.perl.org/functions/use.html
1)形式:
use Module;
use只能够使用模块,而且和require的用法相似,需要Module.pm的文件,而且文件中的package需要已Module来命名该模块。

main.pl

#!C:perlbinperl -w
use strict;
use Show;
Show::show_header();

Show.pm

#Show.pm
package Show;
sub show_header(){
    print "This is the header!  ";   
    return 0;
}
sub show_footer(){
    print "This is the footer!  ";   
    return 0;
}
1;
__END__

2)require和use的区别:
require:
do the things at run time; (运行时加载)
use:
do the things at compile time; (编译时加载)

4. perlmod - Perl modules (packages)
参考http://perldoc.perl.org/perlmod.html
1)  示例:


#Show.pm
package Show;
sub show_header(){
    print "This is the header! /n";  
    return 0;
}
sub show_footer(){
    print "This is the footer! /n";  
    return 0;
}
1;
__END__

2)
一般文件名需要和package名称相同,这里为Show;
可以定义变量和函数;
不要忘记1;
以及最后的__END__

3)
在别的文件中,使用require或者use使用模块的时候:


use Show;
#require Show;
Show::show_header();

5. Perl的函数定义及调用:
 


sub fun_name(){
 #...
}

1) 如果定义在使用之前,在使用的时候直接fun_name();即可
2)如果定义在使用之后,之前使用的时候需要使用&fun_name();来调用函数。

6.
小结:
综上,文件包含可以提高代码的复用性,在Perl是实现文件包含可以才去两条路:
1)使用do或者require(带引号的)那种方式;
2)使用require Module或者use Module的模块方式;
两者均可。