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

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

问题描述

我最近写了一个新的Perl脚本来基于进程名称/用户名来终止进程,并使用类扩展它,以便我可以在其他程序中重用进程代码。我现在的布局是 -

  / home / mutew / src / prod / pskill<  -  Perl脚本
/ home / mutew / src / prod / Process.pm< - 处理过程描述的包

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

 使用lib'/ home / mutew / src / prod ; 

但这是一个主要的可移植性问题。任何解决方案,也将允许我将脚本导出到其他系统,没有和更改?






编辑


  1. 由于其简单性和核心模块的使用,我选择了depesz答案为正确的。

  2. brian d foy的回答虽然表明其他方法完成相同(TMTOWTDI),他在perlfaq8中的贡献使得这个问题绝对是多余的。


解决方案

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

 使用FindBin; 
使用lib $ FindBin :: Bin;

一般来说,我喜欢让我的脚本以这样一种方式提供,程序在任何/ bin中,在这些情况下,我使用一种稍微复杂的方法:

 使用Cwd qw(abs_path); 
使用FindBin;
使用lib abs_path($ FindBin :: Bin /../ lib);

abs_path调用是使@INC包含任何/ lib,而不是任何/ bin /。 ./lib - 这只是一个轻微的变化,但是使阅读错误信息更容易。


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

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?


EDIT

  1. I chose 'depesz' answer as the correct one because of its simplicity and core module usage.
  2. brian d foy's answer though suggests other methods to accomplish the same (TMTOWTDI), his contribution in perlfaq8 renders this question absolutely redundant.

解决方案

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

use FindBin;
use lib $FindBin::Bin;

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");

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天全站免登陆