代码之家  ›  专栏  ›  技术社区  ›  codeholic

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

  •  6
  • codeholic  · 技术社区  · 15 年前

    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 , require ,或 use 是您指定的文件名(使用 值是

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

    怎么办 %公司

    2 回复  |  直到 15 年前
        1
  •  2
  •   Greg Bacon    15 年前

    既然它是一个标准模块,那么使用 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;
    }
    
        2
  •  1
  •   Eric Strom    15 年前

    下面是一个相当健壮的实现,它也适用于尚未加载的模块。

    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;