Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I load a file relative to a module path?

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?

like image 593
Karel Bílek Avatar asked Sep 23 '09 00:09

Karel Bílek


1 Answers

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.

like image 87
ysth Avatar answered Oct 13 '22 09:10

ysth