%INC的键和值是否依赖于平台?

时间:2010-02-23 14:15:32

标签: perl cross-platform perlvar

我想获取包含模块的完整文件名。请考虑以下代码:

package MyTest;

my $path = join '/', split /::/, __PACKAGE__;
$path .= ".pm";

print "$INC{$path}\n";

1;

$ perl -Ipath/to/module -MMyTest -e0
path/to/module/MyTest.pm

它适用于所有平台吗?

perlvar

  

哈希%INC包含条目   通过do包含的每个文件名,   requireuse运营商。钥匙   是您指定的文件名(使用   模块名称转换为路径名),   而值是该位置   找到档案。

这些密钥是否依赖于平台?我应该使用File::Spec还是什么? win32上的至少ActivePerl使用/而不是\

更新%INC值如何?它们是否依赖于平台?

2 个答案:

答案 0 :(得分:2)

鉴于它是标准模块,请使用Module::Loaded的方法:

sub is_loaded (*) { 
    my $pm      = shift;
    my $file    = __PACKAGE__->_pm_to_file( $pm ) or return;

    return $INC{$file} if exists $INC{$file};

    return;
}

sub _pm_to_file {
    my $pkg = shift;
    my $pm  = shift or return;

    my $file = join '/', split '::', $pm;
    $file .= '.pm';

    return $file;
}

答案 1 :(得分:1)

这是一个相当强大的实现,也适用于尚未加载的模块。

use File::Find;
use File::Spec;

sub pkg2path (*) {
    my $file = join '[\\\/:]' =>
               map  "\Q$_"    =>
               split /::|'/   => "$_[0].pm";            # '

    /$file$/ and return File::Spec->rel2abs( $INC{$_} )
        for keys %INC;

    # omit the rest to only find loaded modules

    my $path; find {
        no_chdir => 1,
        wanted   => sub {
            $path = $_ and goto found if /$file$/
        }
    } => @INC;

    found: File::Spec->rel2abs($path or return)
}

say pkg2path Benchmark;
say pkg2path Devel::Trace;