在Perl中,.pm(Perl模块)和.pl(Perl脚本)文件有什么区别? [英] In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?
问题描述
.pm
(Perl模块)和.pl
(Perl脚本)文件之间有什么区别?
What is the Difference between .pm
(Perl module) and .pl
(Perl script) file?
也请告诉我为什么我们从文件中返回1
.如果返回2或其他任何内容,它不会产生任何错误,那么为什么我们要从Perl模块返回1
?
Please also tell me why we return 1
from file. If return 2 or anything else, it's not generating any error, so why do we return 1
from Perl module?
推荐答案
从根本上说,您使用的文件扩展名对于perl
解释这些文件的方式没有影响.
At the very core, the file extension you use makes no difference as to how perl
interprets those files.
但是,将模块放在遵循包名称的某个目录结构的.pm
文件中会带来方便.因此,如果您有模块Example::Plot::FourD
,并将其放在 use
和use Example::Plot::FourD中那样给定包名称时,="http://perldoc.perl.org/functions/require.html" rel ="noreferrer"> require
会做正确的事情.
However, putting modules in .pm
files following a certain directory structure that follows the package name provides a convenience. So, if you have a module Example::Plot::FourD
and you put it in a directory Example/Plot/FourD.pm
in a path in your @INC
, then use
and require
will do the right thing when given the package name as in use Example::Plot::FourD
.
文件必须作为最后一条语句返回true,以指示任何初始化代码的成功执行,因此习惯上以
1;
结尾此类文件,除非您确定否则将返回true.但是最好放1;
,以防您添加更多的语句.
The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with
1;
unless you're sure it'll return true otherwise. But it's better just to put the1;
, in case you add more statements.
如果EXPR
是空词,则require
假定扩展名为".pm",并用文件名中的"/"替换"::",以便于加载标准模块.这种加载模块的形式不会冒更改您的命名空间的风险.
If EXPR
is a bareword, the require
assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace.
use
的全部作用是从提供的程序包名称中找出文件名,在BEGIN
块中require
将其命名,然后在程序包上调用import
.没有什么可以阻止您不使用use
而是手动执行这些步骤.
All use
does is to figure out the filename from the package name provided, require
it in a BEGIN
block and invoke import
on the package. There is nothing preventing you from not using use
but taking those steps manually.
例如,下面我将Example::Plot::FourD
软件包放在名为t.pl
的文件中,并将其加载到文件s.pl
中的脚本中.
For example, below I put the Example::Plot::FourD
package in a file called t.pl
, loaded it in a script in file s.pl
.
C:\Temp> cat t.pl
package Example::Plot::FourD;
use strict; use warnings;
sub new { bless {} => shift }
sub something { print "something\n" }
"Example::Plot::FourD"
C:\Temp> cat s.pl
#!/usr/bin/perl
use strict; use warnings;
BEGIN {
require 't.pl';
}
my $p = Example::Plot::FourD->new;
$p->something;
C:\Temp> s
something
此示例显示模块文件不必以1
结尾,任何真实值都可以.
This example shows that module files do not have to end in 1
, any true value will do.
这篇关于在Perl中,.pm(Perl模块)和.pl(Perl脚本)文件有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!