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

Hey I usually
my %args = ( configfile => $configdir.'/'.basename($0,'.pm').'.conf',
when I want to refer to a confile of the same name as the .pl file. Now when I put this code into a module, it doesn't grab the module name but the calling perl script name. How can I get the module filename when calling inside the module itself?

Replies are listed 'Best First'.
Re: returning filename of module used
by jdporter (Paladin) on May 16, 2005 at 19:17 UTC
    Assuming your module is normally named (e.g. named Foo::Bar and stored in a file Foo/Bar.pm), then this should work:
    package Foo::Bar; sub whence { my $fp = __PACKAGE__; $fp =~ s,::,/,g; $fp .= '.pm'; $main::INC{$fp} }
    But I'm sure there are boundary cases where this doesn't quite cut it...

      Note that %INC (and likely @INC) is actually a global global. That is, it is available in every package:

      package Foo; sub whence { my $fp = shift; $fp =~ s=::=/=g; $fp .= '.pm'; $INC{$fp} } package main; use warnings; print Foo::whence('warnings'),$/;
      Works just fine. ;-) I make minor changes to your example because I didn't use a "normally named" package to put whence into.

Re: returning filename of module used
by davidrw (Prior) on May 16, 2005 at 19:22 UTC
    try __FILE__ instead of $0 or __PACKAGE__

    Update: To be a little cleared, maybe:
    my %args = ( configfile => $configdir.'/'.basename(__FILE__,'.pm').'.conf',
      cool. I'll try that.
Re: returning filename of module used
by jeffa (Bishop) on May 16, 2005 at 19:16 UTC

    I'm not sure if this is the best way, but you could use __PACKAGE__.

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
Re: returning filename of module used
by ikegami (Patriarch) on May 16, 2005 at 20:02 UTC
    To me, it seems better for the main program to supply the configuration options to the module, rather than the module fetching them directly. At the very least, the main program should specify the file name of the configuration file. If you don't, the module's reusability is limited because it's forced to use a single set of configuration options.