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

I'm not worthy. My Perl foo is weak.

I'm searching for how to output the name of the module which is currently running without resorting to defining my own strings. ie. something more rigorous than the following feeble attempt:

#!/bin/env perl my $s = "I'm in main!\n"; print $s; package foo; my $s = "I'm in package foo!\n"; print $s;

Is there hope for the unwashed? I humbly thank you for any enlightenment shared.

Replies are listed 'Best First'.
Re: finding module name?
by kyle (Abbot) on Jan 24, 2009 at 01:53 UTC
    print __PACKAGE__, "\n";

    Update: perldata calls this a "special literal". See the documentation there for details.

Re: finding module name?
by Marshall (Canon) on Jan 24, 2009 at 03:59 UTC
    The previous post about package name is quite correct. I don't know exactly what you are trying to do accomplish. I am just guessing that what you want is more than you asked about.
    This may or not be helpful.

    The reason to know "where you are", often comes about when your program "dies". Since you said that you are new at Perl, you should be aware of this fine point about "die".

    open(IN, "foo") || die "can't open foo"; #versus# open(IN, "foo") || die "can't open foo\n";
    If you do not put a '\n' on the die, you get executing name and line number. If you put the '\n', you just get what you typed in between the double quotes.

    With Perl, you can learn amazing things about what is going on. For example:

    sub whoami { (caller(1))[3] }; #name of the sub that called this sub sub whowasi { (caller(2))[3] }; #name of the parent of that sub
    I'm just guessing that the most important info that you need is "who called me?" when some sub in a package has a problem.
Re: finding module name?
by lakshmananindia (Chaplain) on Jan 24, 2009 at 04:29 UTC
    perl -le 'package foo ;print eval('__PACKAGE__');'

      You don't need the eval; __PACKAGE__ doesn't interpolate by itself, but think of it as a package-scoped constant.