Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

__PACKAGE__ variable cannot use as replace of package name

by chinaxing (Acolyte)
on Apr 23, 2013 at 06:27 UTC ( #1030047=perlquestion: print w/replies, xml ) Need Help??
chinaxing has asked for the wisdom of the Perl Monks concerning the following question:

I know the __PACKAGE__ will be compiled as package name at compile time. so why i cann't use it this way:

in the Foo package's namespace?

this will cause the error :

Undefined subroutine &__PACAKGE__::bar called very thank you !

Replies are listed 'Best First'.
Re: __PACKAGE__ variable cannot use as replace of package name
by moritz (Cardinal) on Apr 23, 2013 at 07:24 UTC
    Undefined subroutine &__PACAKGE__::bar called

    First of all you misspelled PACKAGE, which is not a good thing to do.

    But the real reason is that __PACKAGE__ is only handled specially when it's a term on it own, not when it's part of a name.

    And finally __PACKAGE__ as a separate term becomes a string, and you can't write "MyPackage"::bar() either.

Re: __PACKAGE__ variable cannot use as replace of package name
by kcott (Canon) on Apr 23, 2013 at 08:16 UTC

    G'day chinaxing,

    I see ++moritz has described why you can't do this.

    Here's a way you might emulate the behaviour you're after.

    $ perl -Mstrict -Mwarnings -E ' package Testonly; our $VERSION = "1.000"; { no strict "refs"; say "NO REFS: ", ${__PACKAGE__ . "::VERSION"}; } eval { say ${__PACKAGE__ . "::VERSION"}; }; warn "REFS: $@" if $@; ' NO REFS: 1.000 REFS: Can't use string ("Testonly::VERSION") as a SCALAR ref while "st +rict refs" in use at -e line 9.

    Note how I've used an anonymous namespace to isolate ${__PACKAGE__ . "::VERSION"} in a scope that doesn't check for "strict refs". The eval that follows, demonstrates that the "no strict "refs";" is no longer in effect outside the anonymous namespace.

    -- Ken

Re: __PACKAGE__ variable cannot use as replace of package name
by choroba (Chancellor) on Apr 23, 2013 at 07:45 UTC
    Crossposted at StackOverflow. It is considered polite to inform about crossposting so users not attending both sites do not waste their efforts on a problem already solved at the other corner of the Internet.
    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1030047]
Approved by moritz
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (2)
As of 2016-10-25 01:12 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (313 votes). Check out past polls.