如何加载相对于模块路径的文件? [英] How do I load a file relative to a module path?

查看:105
本文介绍了如何加载相对于模块路径的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何在Perl中做一件事情,我觉得我做的事情根本上是错误的.

我正在做一个更大的项目,所以我将任务分为不同的模块.我将模块放入项目目录的"modules/"子目录中,并将此目录添加到PERL5LIB和PERLLIB.

所有这些模块都使用某些配置,如果从模块文件的角度来看,它们保存在主项目目录的外部文件中,即"../configure.yaml".

但是,现在,当我通过"use"使用模块时,使用这些模块从脚本的当前目录中获取模块中的所有相对路径,而不是从模块本身的目录中获取.即使当我使用FindBin或其他任何东西时,也没有.

如何从模块路径相对加载文件?甚至有可能/建议吗?

解决方案

Perl在%INC哈希中存储从中加载模块的位置.您可以加载与此相关的内容:

package Module::Foo;
use File::Spec;
use strict;
use warnings;

my ($volume, $directory) = File::Spec->splitpath( $INC{'Module/Foo.pm'} );
my $config_file = File::Spec->catpath( $volume, $directory, '../configure.yaml' );

%INC的密钥基于::到/附加/pm的严格翻译,即使在.pm上也是如此. Windows,VMS等

请注意,如果将相对目录放在@INC中,则%INC中的值可能是相对于当前目录的,因此,如果在需求/使用和检查%INC之间更改目录,请务必小心.

I don't know how to do one thing in Perl and I feel I am doing something fundamentally wrong.

I am doing a larger project, so I split the task into different modules. I put the modules into the project directory, in the "modules/" subdirectory, and added this directory to PERL5LIB and PERLLIB.

All of these modules use some configuration, saved in external file in the main project directory - "../configure.yaml" if you look at it from the module file perspective.

But, right now, when I use module through "use", all relative paths in the module are taken as from the current directory of the script using these modules, not from the directory of the module itself. Not even when I use FindBin or anything.

How do I load a file, relative from the module path? Is that even possible / advisable?

解决方案

Perl stores where modules are loaded from in the %INC hash. You can load things relative to that:

package Module::Foo;
use File::Spec;
use strict;
use warnings;

my ($volume, $directory) = File::Spec->splitpath( $INC{'Module/Foo.pm'} );
my $config_file = File::Spec->catpath( $volume, $directory, '../configure.yaml' );

%INC's keys are based on a strict translation of :: to / with .pm appended, even on Windows, VMS, etc.

Note that the values in %INC may be relative to the current directory if you put relative directories in @INC, so be careful if you change directories between the require/use and checking %INC.

这篇关于如何加载相对于模块路径的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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