Determine the absolute path of the module without using

In some cases, you need to determine the absolute path name of the Perl module, but you do not need to load the Perl module:

use strict; use warnings; my $mod_name = 'My::Module'; my $abs_path = mod_name_to_abs_path( $mod_name ); sub mod_name_to_abs_path { my ( $mod_name ) = @_; my $rel_fn = $mod_name =~ s{::}{/}gr; $rel_fn .= '.pm'; require $rel_fn; return $INC{$rel_fn}; } 

The above code loads the module (via require ).

How to determine the absolute name of a module path without using require?

+3
source share
2 answers

Module::Util provides a find_installed function that does what it seems to you.

There is also an object-oriented Module::Info and Module::Data that will do something that looks similar

This program shows the use of all three

 use strict; use warnings 'all'; use feature 'say'; use Module::Util 'find_installed'; use Module::Info (); use Module::Data (); say find_installed('Module::Util'); say Module::Info->new_from_module('Module::Info')->file; say Module::Data->new('Module::Data')->path; 

Output

 C:\Strawberry\perl\site\lib\Module\Util.pm C:\Strawberry\perl\site\lib\Module\Info.pm C:\Strawberry\perl\site\lib\Module\Data.pm 
+6
source

I am posting this solution to my question, because I could not find the CPAN module that did this.

 use strict; use warnings; use File::Spec; my $mod_name = 'My::Module'; my $abs_path = mod_name_to_abs_path( $mod_name ); sub mod_name_to_abs_path { my ( $mod_name ) = @_; my $rel_fn = $mod_name =~ s{::}{/}gr; $rel_fn .= '.pm'; my $abs_path; for my $dir (@INC) { if ( !ref( $dir ) ) { my $temp = File::Spec->catfile( $dir, $rel_fn ); if ( -e $temp ) { if ( ! ( -d _ || -b _ ) ) { $abs_path = $temp; last; } } } } return $abs_path; } 
+7
source

Source: https://habr.com/ru/post/1265734/


All Articles