In Perl, there is no pre-defined constructor. More generally, in Perl, an object is just a reference associated with a package (the class). bless is the function that does that. This doesn't even have to be in an constructor.
my $obj = {}; # empty anonymous hash reference
bless $obj, "Some::Class";
With only one argument, bless associates the reference with the current package, whatever that is.
package Some::Class;
my $obj = {};
bless $obj; # blesses into "Some::Class"
There is no default constructor in Perl -- though by convention, it's usually called new. When perl calls a method, the invoking object or package name is passed as the first argument.
$obj->method( 'foo' ); # @_ contains ( $obj, 'foo' )
Some::Class->method( 'foo' ); # @_ contains ( 'Some::Class', 'foo' )
So the constructor needs to look at the first argument to find the class name. If the first argument is a object (checking ref), the class is the result of ref. Otherwise, the first argument is the class name.
package Some::Class;
sub new {
my $first_arg = shift; # get the first argument
my $class = ref($first_arg) || $first_arg;
my $self = {}; # create a new, anonymous reference;
bless $self, $class: # bless it into the class
return $self;
}
The variations are mostly shortcuts of all those separate statements. However, if the single-argument form of bless is called, the constructor always blesses into the current package -- which won't work for subclasses. By using the two-argument form, subclasses can inherit new and the object will be properly blessed into the subclass (which is passed as the first argument). Likewise, some people don't like $obj->new() and so don't bother to check ref -- they just require the constructor to only be called as a class method.
-xdg
Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.
|