Does __PACKAGE__ use bad methods for inheritance inside my methods?

If inside my code I get calls like:

__PACKAGE__->method; 

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

+6
oop perl
source share
4 answers

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

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

+3
source share

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 parent 'A'; package main; my $b = B->new; $b->method1; $b->method2; 

Output:

  Hello from: A
 Hello from: B
+9
source share

If you intend to inherit this method, call it by the referent and do not rely on the package in which you find it. If you intend to call a method internal to a package that another package should not see, then this may be good. There is a more complete explanation in Intermediate Perl and, possibly, in perlboot (which is an extract from the book).

In general, I try to never use __PACKAGE__ unless I write modulino .

Why are you trying to use __PACKAGE__ ?

+6
source share

"It depends". this is the correct answer. Actually a relatively simple package name; usually you will have an instance or class name to start with. However, there are times when you really need the package name - __PACKAGE__ - this is obviously a tool for this work that is superior to the literal one. Here are some suggestions:

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

Try to avoid __PACKAGE__ inside methods in general. Each use of __PACKAGE__ adds a bit of inflexibility. Sometimes inflexibility is what you want (because you need permission at compile time or have poor control over where the information is stored), but be sure that what you want is worth it. You will thank yourself later.

Outside of methods, you do not have access to $self and must call off __PACKAGE__ methods, not a literal. This is mainly important for compile-time declarations, similar to those provided by Class::Accessor .

+3
source share

All Articles