我的 Perl 脚本如何在同一目录中找到它的模块? [英] How can my Perl script find its module in the same directory?

查看:20
本文介绍了我的 Perl 脚本如何在同一目录中找到它的模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近编写了一个新的 Perl 脚本来根据进程名/用户名终止进程,并使用类对其进行扩展,以便我可以在其他程序中重用进程代码.我目前的布局是 -

I recently wrote a new Perl script to kill processes based on either process name / user name and extended it using Classes so that I could reuse the process code in other programs. My current layout is -

/home/mutew/src/prod/pskill       <-- Perl script
/home/mutew/src/prod/Process.pm   <-- Package to handle process descriptions

我在 $PATH 变量中添加了 ~/src/prod 以从任何地方访问脚本.在从其驻留目录以外的任何目录运行脚本时,会导致无法在 @INC 中找到 Process.pm"(这是可以理解的,因为除了/usr 中的共享目录,@INC 仅包括当前目录 -'.').我一直在使用的一种解决方法是使用 lib 指令 -

I added ~/src/prod in my $PATH variable to access the script from anywhere. On running the script from any directory other than its resident directory leads to a "Can't locate Process.pm in @INC" (which is understandable given that other than the shared directories in /usr, @INC includes only the current directory - '.'). One workaround that I have been using is the use lib directive as so -

use lib '/home/mutew/src/prod';

但这是一个主要的可移植性问题.任何解决方案也可以让我将脚本导出到其他系统而无需更改?

but this is a major portability issue. Any solutions which will also allow me to export the script to other systems without and changes?

编辑

  1. 我选择了 'depesz' 作为正确答案,因为它的简单性和核心模块用法.
  2. brian d foy 的回答虽然提出了其他方法来完成相同的任务 (TMTOWTDI),但他在 perlfaq8 中的贡献使这个问题完全多余.

推荐答案

我发现最简单的方法是使用 FindBin 模块.像这样:

The simplest approach I found it to use FindBin module. Like this:

use FindBin;
use lib $FindBin::Bin;

通常我更喜欢以这样一种方式提供我的脚本,即程序在任何/bin中,而库在whatever/lib中

Generally I prefer to have my scripts provided in such a way that programs are in whatever/bin, and libraries are in whatever/lib

在这些情况下,我使用稍微复杂的方法:

In these situations I use a slightly more complicated approach:

use Cwd qw(abs_path);
use FindBin;
use lib abs_path("$FindBin::Bin/../lib");

abs_path 调用是为了让@INC 包含whatever/lib,而不是whatever/bin/../lib - 这只是一个微小的变化,但使阅读错误消息更容易.

The abs_path call is to make the @INC contain whatever/lib, and not whatever/bin/../lib - it's just a slight change, but makes reading error messages easier.

这篇关于我的 Perl 脚本如何在同一目录中找到它的模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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