我如何告诉 perl 模块的路径?
我在 Perl 脚本中使用 Perl 模块文件:
printtab.pl
use Table;
Table.pm
与 printtab.pl
位于同一目录中,因此只要我从目录中执行 printtab,它就可以正常执行。
但是,如果我从其他地方执行它,例如使用 cronjob,我会收到一条错误,指出在 @INC
中找不到该模块。
解决这个问题的正确方法是什么?
我尝试过
push @INC, "/path/Table.pm";
,但不起作用。 你能告诉我为什么吗?
我发现use lib
并且它工作正常
use lib "/path";
在这种情况下use lib是最好的方法吗?
I use a perl module file in my perl script:
printtab.pl
use Table;
Table.pm
is present in the same directory as printtab.pl
, so as long as I am executing printtab from the directory, it executes fine.
But If I execute it from some other place, for example, using a cronjob, I get an error mentioning that the module is not found in @INC
.
What is the correct way to resolve this?
I tried
push @INC, "/path/Table.pm";
but it does not work. Can you tell me why?
I found about use lib
and it works correctly
use lib "/path";
Is use lib the best method in such a situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 lib
是一个不错的选择。但是,如果您将模块放置在与程序相同的目录中(或者放置在与包含程序的目录相关的子目录中),则可以使用use FindBin;
,例如:use lib
is a good option. But is you place your modules in the same directory as your programs (or in a sub-directory relative to the one containing your programs), you could useuse FindBin;
like:不起作用,因为 @INC 应该是目录列表,而不是模块的完整路径。所以如果你这样做:
它应该有效。
话虽如此,
use lib "/path";
也是一个不错的选择。根据程序的安装目录结构,使用 FindBin 确定脚本的真实位置可能有助于构建模块的正确路径。
Does not work because @INC is supposed to be a list of directories, not of full paths to modules. So if you do:
It should work.
Having said that,
use lib "/path";
is also a good option.Depending on your programs' install directory structure using the FindBin to determine the real location of your script may prove useful to construct the correct path to your module.
一个巧妙的小技巧:
我对
$main::moduleIsMissing
事情不满意,但我还没有找到解决方法。如果
My::Module
可用,则它已加载并且一切正常。否则,$main::moduleIsMissing
标志被设置。这允许您测试模块是否已加载,如果没有加载,则采取规避操作。例如,如果模块Term::Cap
可用,您的程序在打印文本时将使用粗体,但如果不可用,则将简单地打印出没有粗体的文本。回到问题:这样做要好得多:
而不是
@INC
。use lib
在编译时包含该目录。因此,如果我在目录“MyDir”中有一个模块“Foo::Bar”,我可以这样做:没有 Perl 抱怨。如果我这样做:
Perl 会抱怨它找不到我的模块。
A neat little trick:
I'm not happy about the
$main::moduleIsMissing
thing, but I haven't figured a way around it.If
My::Module
is available, it's loaded and everything is fine. Otherwise, the$main::moduleIsMissing
flag is set. This allows you to test to see if the module was loaded, and if not, take evasive action. For example, your program will use boldfacing when printing text if moduleTerm::Cap
is available, but if not, will simply print out the text sans the boldface.Back to the question: It's much better to do:
Rather than the
@INC
.The
use lib
includes the directory at compile time. Thus, if I had a module "Foo::Bar" in directory "MyDir", I could do this:without Perl complaining. If I did this:
Perl would complain it can't find my module.