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

The Scenario

The special variable known as $0 works as desired when it is inside a script (eg, 'fooScript.pl'). However, when the happy camper retrofits his script code into a perl module (eg 'fooModule.pm'), the happy camper becomes sad. Why? Because $0 doesn't report the name of the *module*, it reports the name of the *calling script* (eg 'fooScriptThatHappensToUseFooModulePM.pl) .

The Question

The happy camper doesn't have a complaint with the way $0 works, that's sensible enough, but is there an alternative to $0? The happy camper wishes for a special variable that reports the name of the *perl module file* in which it is located. Is there such a thing?

Replies are listed 'Best First'.
Re: Searching for an alternative to $0
by Plankton (Vicar) on May 18, 2004 at 21:33 UTC
    Try using __FILE__ as in ...
    print __FILE__ . "[" . __LINE__ ."] Hi there\n";

    Plankton: 1% Evil, 99% Hot Gas.
Re: Searching for an alternative to $0
by duff (Parson) on May 18, 2004 at 21:29 UTC
    There's the compile time "directive" __PACKAGE__ or you could fiddle with caller.

    Update I just re-read what you wrote. __FILE__ might be more of what you're looking for.

Re: Searching for an alternative to $0
by jmcnamara (Monsignor) on May 18, 2004 at 21:28 UTC

    See __PACKAGE__ in perldata.
    #!/usr/bin/perl -wl print __PACKAGE__; package My::Package; print __PACKAGE__; __END__ Prints: main My::Package

    Update: As per the comment below, if you want the filename and not the package name then you should use __FILE__, also in perldata.

    --
    John.

      Considering the OP is asking for a filename, and your proposed solution using __PACKAGE__ gives two different results for the same file, it's obvious your solution can't be correct.

      Abigail

Re: Searching for an alternative to $0
by ambrus (Abbot) on May 18, 2004 at 21:53 UTC
Re: Searching for an alternative to $0
by zude (Scribe) on May 18, 2004 at 21:46 UTC
    caller, eh? OK then, how about:
    $my_name = sub{($a=(caller)[0])eq'main'?$0:$a}->();

    +++++++++ In theory, theory describes reality, but in reality it doesn't.

Re: Searching for an alternative to $0
by eserte (Deacon) on May 19, 2004 at 09:55 UTC
    For the sake of completness: there's also the %INC variable. If, for instance, you included a module with "use Foo::Bar", then the value of $INC{"Foo/Bar.pm"} would be the absolute or relative path of the module. I'm not sure if the resulting value is always the same as __FILE__.