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?
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__ } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With