perl - 在 Perl 中,.pm(Perl 模块)和 .pl(Perl 脚本)文件有什么区别?

标签 perl perl-module

.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 the 1;, in case you add more statements.

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做的是从提供的包名中找出文件名,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/

相关文章:

regex - 在 perl 中,如何模式匹配字符串以查看一行中是否存在回车符

从 C 调用 Perl 函数会导致崩溃

perl - 如何运行 passwd -S 并在 Perl 中捕获其输出?

perl - 使用 Net::SSH::Perl 登录远程机器

perl - Text::CSV perl 模块中的 is_quoted() 方法

linux - 简单的 perl opendir

perl - 如何在 perl 中专门读取文件?

perl - 更新命令行输出

windows - ExtUtils::MakeMaker 和 Windows 上支持的 MAKE 程序

perl - 为什么 sub 中的 use 语句全局适用?