A conventional constructor looks like:
package MyObject;
sub new {
my ($package, @args) = @_;
my $self = { };
... use @args, initialize $self ...
return bless $self, $package; # or sometimes bless $self,__PACKAGE__
}
It is the bless
statement that assigns a "type" to the data structure in $self
. Usually, the second argument to bless
is the name of the current package. But this is Perl, so you don't always have to do things the usual way. Even in the constructor for MyObject
, you don't have to pass MyObject
to bless
:
package MyObject;
sub new {
my ($package, %args) = @_;
my $self = { };
... use @args, initialize $self ...
if ($args{"type"} == 1) { $package = "MyObject::Foo"; }
elsif ($args{"type"} == 2) { $package = "MyObject::Bar"; }
elsif ($args{"type"} == 3) { ... }
return bless $self, $package;
}