I've seen two ways to implement the new
method in a derived class.
Method one:
sub new {
my $invocant = shift;
my $class = ref($invocant) || $invocant;
my $self = {};
bless($self, $class);
$self = $self->SUPER::new( @_ );
return($self);
}
Method two:
sub new {
my $self = shift;
my $class = ref($self) || $self;
return $self if ref $self;
my $base_object = $class->SUPER::new(@_);
return bless ($base_object, $class);
}
I'm not sure I understand what the difference is. Can anyone please explain?
From your comments and answers I can see that the ref()
part is bad.
But what about the use of SUPER::new(@_)
? In the first example, the hashref is blessed into the derived class and then that object's SUPER
's new
is called and saved into the same object.
In the second example on the other hand, a base object is created from the class's SUPER
s new
method and that is blessed into the new class.
What is the difference between these two ways? It looks like the first overwrites the object with the base object. The second seems to "double-bless". I'm confused.