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; }

In reply to Translating Module Names to File Names by bbfu

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.