tags:

views:

113

answers:

3

I'm refactoring a perl module in legacy code, and this is a function from the module:

sub get_user {
    my $user = __PACKAGE__->{user};
    if (!defined $user) {
       # more code
       __PACKAGE__->{user} = $user;
    }
    return $user;
}

This module compiles under use strict. And there's no package variables defined. What does __PACKAGE__->{user} mean?

+1  A: 

__PACKAGE__->{user} = $user sets the value of user in whatever the current package is.


From perldoc perlmod:

The special symbol __PACKAGE__ contains the current package, but cannot (easily) be used to construct variable names.

Zaid
The OP wasn't asking about __PACKAGE__ specifically, but about the strange use in using it to dereference a hash.
Ether
Yes, my focus was more on answering the title in the question... perhaps I stop and think about what's being asked for a bit longer.
Zaid
A: 

__PACKAGE__ is a hash. This syntax accesses a keyed value.

mcandre
+6  A: 

__PACKAGE__ is the name of the current package; your code is using it as a symbolic hash reference. So if your package is foo, it is setting $foo::foo{'user'}. This is kind of a strange thing to do; I suspect it may be an error.

Because it's a symbolic reference, it shouldn't be allowed under strict. It seems to be, however, at least when the current package has multiple parts (e.g. Foo::Bar, not just Foo). I wouldn't depend on this bug staying in effect, though.

ysth
My guess is that `__PACKAGE__` in *eugene y*'s example is a `Compound::Namespace::Construction` rather than `SimpleOne` (no colons), which seems to circumvent stricture for me under 5.10.
pilcrow
... of course! Because `__PACKAGE__->{key}` in a simple namespace is, e.g., `main->{key}` (error: `Global symbol "%main" requires explicit package name`), but in a compound namespace is, e.g., `My::Pkg->{key}`, which is a fully qualified reference to the hash `%Pkg` under package `My`. I would expect a "bareword" error, but the special processing of `__PACKAGE__ must sidestep that.
pilcrow
ah. that seems like a bug to me.
ysth
Somebody please report this bug. :)
Ether