Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

__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:

__PACKAGE__::bar()
in the Foo package's namespace?

this will cause the error :

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

Comment on __PACKAGE__ variable cannot use as replace of package name
Select or Download Code
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 (Abbot) 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 (Canon) 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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (10)
As of 2015-07-07 23:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (93 votes), past polls