如何加载相对于模块路径的文件?

编程入门 行业动态 更新时间:2024-10-24 14:16:00
本文介绍了如何加载相对于模块路径的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我不知道如何在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.

更多推荐

如何加载相对于模块路径的文件?

本文发布于:2023-10-31 16:34:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1546649.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:相对于   路径   模块   加载   文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!