tags:

views:

123

answers:

4

If inside my code I'll have calls like:

__PACKAGE__->method;

will this limit the usability of this module, if this module is inherited?

+3  A: 

That depends. Sometimes __PACKAGE__->method() is exactly what you need.

Otherwise it's better to use ref($self)->class_method() or $self->method().

Peter Stuifzand
But if you plan on your class getting inherited, it's a bad thing, right?
Geo
@Geo: It depends.
Sinan Ünür
If `__PACKAGE__` is what you need, you should use that. It could be a problem and you should check if you get the results you expect.
Peter Stuifzand
+7  A: 

It depends on what you want to do:

#!/usr/bin/perl

package A;

use strict; use warnings;

sub new { bless {} => $_[0] }

sub method1 {
    printf "Hello from: %s\n", __PACKAGE__;
}

sub method2 {
    my $self = shift;
    printf "Hello from: %s\n", ref($self);
}

package B;

use strict; use warnings;
use base 'A';

package main;

my $b = B->new;

$b->method1;
$b->method2;

Output:

Hello from: A
Hello from: B
Sinan Ünür
+6  A: 

If you intend to inherit that method, call it on the referent and don't rely on the package you find it in. If you intend to call a method internal to the package that no other package should be able to see, then it might be okay. There's a fuller explanation in Intermediate Perl, and probably in perlboot (which is an extract of the book).

In general, I try not to ever use __PACKAGE__ unless I'm writing a modulino.

Why are you trying to use __PACKAGE__?

brian d foy
I used it out of convenience, so that I wouldn't need to get the package name.
Geo
Okay, but why were you trying to get the package name? You probably shouldn't be doing that no matter how you get the name.
brian d foy
+2  A: 

"It depends." is the correct answer. It is relatively uncommon to actually need the package name; usually you will have an instance or a class name to start with. That said, there are times when you really do need the package name -- __PACKAGE__ is clearly the tool for that job, being superior to a literal. Here are some guidelines:

Never call methods off __PACKAGE__ inside methods, as doing so makes it impossible for inheritors to change your implementation by simply overriding the called method. Use $self or $class instead.

Try to avoid __PACKAGE__ inside methods in general. Every use of __PACKAGE__ adds a little bit of inflexibility. Sometimes, inflexibility is what you want (because you need compile-time resolution or badly want to control where information is being stored), but be triply sure that what you want is worth the cost. You'll thank yourself later.

Outside of methods, you don't have access to a $self, and should call methods off __PACKAGE__ rather than a literal. This is mostly important for compile-time declarations like those provided by Class::Accessor.

darch