in reply to Syntax for preventing repeat object initializations

$self is a hashref and __PACKAGE__ is the package in the class that it's in. If this code is in package "Foo", then the '_init' key in self is auto-incremented. The first time this occurs, it will evaluate as false, allowing Foo::_init to function, but subsequent calls will fail.

nysus wrote:

But how does throwing a class, {__PACKAGE__}, on the right side of an object method call, $self->{_init}, create an attribute?

You're simply auto-vivifying a hash key with the name being equal to the current package name. You see, Perl has an interesting shortcut for complex data structures. In this case, the following are equivalent:

$self->{_init}->{__PACKAGE__}; $self->{_init}{__PACKAGE__};
If you've dereferenced the first reference, you're allowed to drop the arrow notation for subsequent dereferences. Thus, $self->{_init} becomes a hashref on the fly by merely appending curly braces.

Cheers,
Ovid

Vote for paco!

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.