Well, one piece of advice for OO in Perl which I myself picked up from this site (in
dws's comments
here), is that it's a tidy piece of good practice to separate your
blessing from actually initialising your object variables. This requires 2 methods, which you might as well call
sub new and
sub initialise.
So for your constructor, you'd have:
package Food;
sub new
{ my $class = shift;
my $self = bless {}, $class;
$self->initialize;
$self;
}
sub initialize {
my $self = shift;
$self->{_beverage} = "Pepsi";
$self->{_entree} = "soup";
$self->{_dessert} = "ice cream";
}
I think it's conventional to put an underscore before your object variable names too, eg
_beverage.
This may look like a bit of a waste of space, but its neatness might become a bit more obvious when you are actually passing initialisation info to the constructor (as opposed to everything starting off as Pepsi, soup, ice cream). Then you'd change the line in new to
$self->initialize(@_);, and then have
sub initialize {
my $self = shift;
$self->{_beverage} = shift;
$self->{_entree} = shift;
$self->{_dessert} = shift;
}
Call it with something like
my $meal = new Food("tea", "sushi", "creme egg");
HTH
Dennis
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.