Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Directory of PM file

by tomazos (Deacon)
on Oct 12, 2005 at 08:53 UTC ( [id://499421]=perlquestion: print w/replies, xml ) Need Help??

tomazos has asked for the wisdom of the Perl Monks concerning the following question:

How can you get a handle on the directory that a module is located in from within that module's code?

Lets say you have to write a module called Module.pm and you don't know where it will be installed, or which scripts it will be used by, but you know that in the modules parent directory there are some (grep "../*.foo") files you want to process.

Trouble is that grep is going to be relative to the current directory which is not necessarily the modules directory. To go relative to the module you need to be able to find out where it is.

Is that possible?

-Andrew.

Replies are listed 'Best First'.
Re: Directory of PM file
by sh1tn (Priest) on Oct 12, 2005 at 09:22 UTC
Re: Directory of PM file
by bart (Canon) on Oct 12, 2005 at 10:20 UTC
    How can you get a handle on the directory that a module is located in from within that module's code?

    Try __FILE__. See perldata, section "special literals". Drop the file's basename from that string, possibly using File::Basename.

    A test revealed that this can produce a relative path; rel2abs() from File::Spec::Functions can remedy that.

    For example, test module Foo.pm:

    package Foo; use File::Spec::Functions qw(rel2abs); use File::Basename; my $dir = (fileparse(rel2abs(__FILE__)))[1]; print "Foo directory: $dir\n"; 1;

    IMO it's safest to indeed set a variable with this directory in the top level of the module, as I do here, so it always gets set when the module is loaded.

Re: Directory of PM file
by EvanCarroll (Chaplain) on Oct 12, 2005 at 08:57 UTC
    I would assume you could use $INC{$0} or such from within the script. Methods in File::Spec might be of assist.


    Evan Carroll
    www.EvanCarroll.com

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://499421]
Approved by g0n
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (5)
As of 2024-04-16 09:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found