http://www.perlmonks.org?node_id=909082


in reply to Re: Perl Object Initilization
in thread Perl Object Initilization

you should not redefine $self once you have blessed it into objecthood. Assign to individual keys of the underlying hash instead. In addition to the method given by chromatic above, you can also do it this way (just a slightly different style):
sub init { my $self = shift; my %args = @_; while (my ($attribute, $value) = each %args){ $self->{$attribute} = $value; } }
Here yuo are using the fact that an even-sized list can simply be assigned to a new hash to populate it ( which is what you always do when you say my %hash=( key1 => value2 ) as '=>' is just a glorified comma).
I would also agree that, particularly in this case, a separate init method is not needed, because you are just assigning values to attributes and that can all be done when you construct the hash that you then bless in the 'new' method.
There may be some cases where more complicated setup needs to be done that might be better off in separate subs, such as connections to various databases, but then I would call them things like '_init_db_connection' or whatever you need to do.
I would also second chromatic's suggestion to look into Moose soon. If you are just starting with OO programming in Perl then it's certainly good to see the non-Moose, old style first and understand it but then move on to a more modern object system like Moose. It seems like a bit of a learning curve at the beginning but it's well worth it.