http://qs321.pair.com?node_id=472581


in reply to How do I make a constructor?

I'm a pragmatist, and see nothing wrong with supporting $obj->new(). In fact, perlobj even mentions it. If your class takes args that are in addition to what the parent class uses in ->new(), then you need a bit more code.
# Create a new object sub new { my $thing = shift; my $class = ref($thing) || $thing; my $self = {}; bless($self, $class) if (! $self->_init($thing, @_)) { # Failed to initialize # Throw some sort of error, or return; # Returns 'undef' } return ($self); } # Initialize a new object sub _init { my $self = shift; my $thing = shift; # Separate '@_' into args for parent class and args for this sub +class my @parent_args = ...; my @my_args = ...; # Perform parent class initialization if (! $self->SUPER::_init($thing, @parent_args)) { # Parent class initialization failed return (0); } # Perform subclass initialization # Making use of '@my_args', if any if (ref($thing)) { # $thing->new( ... ) was called # Make use of '@my_args', if any # And make use of object's data, if applicable } else { # CLASS->new( ... ) was called # Make use of '@my_args', if any } return (1); }
Note that $thing is passed to _init() in addition to the args (cf. jamesduncan's code above). When the user calls $obj->new(), this allows the initialization method to make use of data contained in the calling object, if that is applicable to your code.