在 Perl 中,.pm(Perl 模块)和 .pl(Perl 脚本)文件有什么区别? [英] In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

查看:28
本文介绍了在 Perl 中,.pm(Perl 模块)和 .pl(Perl 脚本)文件有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.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 并且你把它放在 Example/Plot/FourD.pm 目录下你的 @INC,然后是 userequire 在给定包名时会做正确的事情,如use Example::Plot::FourD.

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 the 1;, 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 所做的就是从提供的包名中找出文件名,requireBEGIN 块中并调用 在包上导入.没有什么可以阻止您不使用 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
" }

"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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆