在某些情况下,您需要确定 Perl 的绝对路径名
模块,但您不需要加载 Perl 模块:
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};
}
上面的代码加载模块(使用
require
)。如何在不使用 require 的情况下确定模块的绝对路径名?
最佳答案
我将这个解决方案发布到我自己的问题中,因为我找不到执行此操作的 CPAN 模块。
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;
}
关于perl - 在不使用 require 的情况下确定模块的绝对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41707660/