This little function will return the full location (path) for a given module name (or undef if not found). For example, if you pass it 'CGI::Fast', it might return '/usr/lib/perl5/5.00503/CGI/Fast.pm'.
This can be useful for finding the location of a given module that you're using, or for converting the module names (in that nice and easy Module Name Format) to the fully qualified path-to-file so that you can open it for reading or what-have-you.
Note: As posted here, the snippet auto-adds the current directory to the search path (and will double search the current directory if @INC contains it already). This is for convience in finding user-installed modules. You can change this quite easily by removing the '.', part from the foreach loop.
Update:Note also that you can specify a path in the module name and it will search there first (eg: '/CGI' will look for CGI.pm in the root directory first). If not found, it strips off any leading path info and searches for just the file. (I fixed this behaviour slightly (read: I added it real quick), as leading path info messed up the first version I posted.)
Update 2:Fixed a problem with the checking specified paths interfereing with nested modules (eg: Text::Template).
sub mod2file { my $modname = shift or return undef; my $filename = ($modname !~ m|^(.*/)?[^/]*\.[^/]*$|) ? "$modname.pm" : $modname; $filename =~ s|^(.*/)||; # Strip leading path info ... my $startpath = $1; # ... but save it in $startpath. $filename =~ s|::|/|g; return "$startpath$filename" if($modname =~ m|/| and -e "$startpath$filename"); foreach my $basedir ('.', @INC) { return "$basedir/$filename" if(-e "$basedir/$filename"); } return undef; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Translating Module Names to File Names
by chipmunk (Parson) on Feb 21, 2001 at 04:01 UTC | |
by bbfu (Curate) on Feb 21, 2001 at 04:08 UTC | |
|
Re: Translating Module Names to File Names
by japhy (Canon) on Feb 21, 2001 at 03:11 UTC | |
by bbfu (Curate) on Feb 21, 2001 at 03:52 UTC | |
|
Re: Translating Module Names to File Names
by Maclir (Curate) on Feb 21, 2001 at 04:28 UTC | |
by bbfu (Curate) on Feb 21, 2001 at 04:52 UTC | |
by Maclir (Curate) on Feb 21, 2001 at 05:08 UTC | |
by bbfu (Curate) on Feb 21, 2001 at 05:18 UTC |