Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not simply use __PACKAGE__ when creating a new Perl module?

Tags:

module

perl

I wish I knew the reference or document that told me that this is the best way to create a new object in Perl:

sub new {
   my $package = shift;
   my $class = ref($package) || $package

This is how I've been creating objects for years but now I'm wondering why go to the trouble? With the exception of some edge cases why not simply do the following:

sub new {
    shift; # get rid of the object or package name
    my $class = __PACKAGE__;

Are there any issues with simply doing using __PACKAGE__ when there's no special reason to try to detect what namespace the 'new' method is being called in?

like image 583
Skeletonkey Avatar asked Feb 01 '20 00:02

Skeletonkey


1 Answers

Inheritance

# classA.pm 
package ClassA;
sub new { $pkg = ref($_[0]) || $_[0] ; bless { foo => 42 }, $pkg }

# classB.pm
package ClassB;
use parent 'ClassA';
sub foo { ... }

# main.pl
use ClassA;
use ClassB;
$B = ClassB->new();
print $B->foo();

In this example, ClassB inherits methods from ClassA, including its constructor. But we still want to identify the object as belonging to ClassB, so the constructor in ClassA must respect the name of the reference passed to its constructor.

Easier and safer than

$B = bless { ClassA->new(), "ClassB" };   # or
$B = bless { ClassB->new(), "ClassA" };

or adding a pass-though constructor in ClassB.

package ClassB;
use parent 'ClassA';
sub new { bless { ClassA::new(@_), __PACAKGE__ } }
like image 154
mob Avatar answered Nov 05 '22 23:11

mob