Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find out the filename of a Perl package?

I would like to translate a Perl package name to the full path of the file.

say package_name_to_path('Foo::Bar::Baz');
/tmp/Foo/Bar/Baz.pm

I know there is a CPAN module to do this? I just can't find it again?

like image 602
git-noob Avatar asked Feb 19 '09 06:02

git-noob


People also ask

How to get filename in Perl?

use File::Basename; ... $file = basename($path);

What is package name in Perl?

A Perl package is a collection of code which resides in its own namespace. Perl module is a package defined in a file having the same name as that of the package and having extension . pm. Two different modules may contain a variable or a function of the same name.


1 Answers

If you've loaded the module, just look in %INC but you have to do it by filename.

say $INC{"Foo/Bar/Baz.pm"};

If you haven't, you can use Module::Util or the module_info program which comes with Module::Info.

$ module_info Module::Build

Name:        Module::Build
Version:     0.30
Directory:   /usr/local/lib/site_perl
File:        /usr/local/lib/site_perl/Module/Build.pm
Core module: no

Or you can go through @INC manually.

my $module = "Foo::Bar";

# Convert from Foo::Bar to Foo/Bar.pm
my $file   = $module;
$file =~ s{::}{/};
$file .= ".pm";

my $path;
for my $dir (@INC) {
    $path = "$dir/$file";
    last if -r $path;
    $path = undef;
}

say defined $path ? "$module is found at $path" : "$module not found";

(A fully cross platform solution would use File::Spec instead of joining with slashes.)

If you just need to find a module quick, perldoc -l works well as Fayland mentioned, but it will fail to find a module that has no POD.

like image 91
2 revs Avatar answered Sep 18 '22 14:09

2 revs