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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.