.pm
和有什么区别(Perl 模块)和 .pl
(Perl 脚本)文件?
也请告诉我为什么我们返回 1
从文件。如果返回 2 或其他任何值,它不会产生任何错误,那么我们为什么要返回 1
来自 Perl 模块?
最佳答案
从本质上讲,您使用的文件扩展名对于 perl
的方式没有任何影响。解释这些文件。
但是,将模块放入 .pm
遵循包名的特定目录结构的文件提供了便利。所以,如果你有一个模块 Example::Plot::FourD
你把它放在一个目录Example/Plot/FourD.pm
在您的 @INC
中的路径中,然后 use
和 require
如果给定包名,如 use Example::Plot::FourD
所示,将做正确的事情.
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.If
EXPR
is a bareword, therequire
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
做的是从提供的包名中找出文件名,require
它在 BEGIN
阻止并调用 import
包装上。没有什么可以阻止您不使用 use
但手动采取这些步骤。例如,下面我把
Example::Plot::FourD
打包在一个名为 t.pl
的文件中,将其加载到文件 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
结尾。 ,任何真值都可以。
关于perl - 在 Perl 中,.pm(Perl 模块)和 .pl(Perl 脚本)文件有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3402821/